2010年9月7日 星期二

[How TO]把facebook iphone sdk導入你的iphone app(1)

1.建立view-based app:假設叫做facebooktest
ishot-1.png


抓取facebook官方製作的facebook for iphone sdk

3.打開src目錄裡頭的facebook_iphone_sdk.xcodeproj
把FBconnect目錄抓到你的app之中。

ishot-2.png


4.打開專案的info FBCONNECT 的src路徑加到專案的header search path裡頭。
ishot-3.png

ishot-5.png  




5.找到專案裡頭的application的Delegate和一個viewcontroller
viewcontroller部分,

.h file
#import <uikit/uikit.h>
#import "FBConnect/FBConnect.h"
 
@interface facebooktestViewController : UIViewController <fbsessiondelegate,fbdialogdelegate,fbrequestdelegate>{
 IBOutlet FBLoginButton *_fbloginbutton;
 IBOutlet UIButton *_fpost;
 FBSession *_session;
}
 
- (void)session:(FBSession*)session didLogin:(FBUID)uid;
- (void)sessionDidLogout:(FBSession*)session;
-(void)post_to_facebook:(id)sender;
 
@end

.m file 主要要修改幾個部分
定義應用程式api key和 api secret
(到facebook developer上面去申請自己的應用程式,會得到應用程式的key和secret,現在我申請了應用程式fbtry作為例子。)

ishot-7.png




viewcontroller initWithNib做修改如下,這樣系統才會知道切到viewcontroller時該連結哪一個nib file:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:@"facebooktestViewController" bundle:nibBundleOrNil]) {
        if (kGetSessionProxy) {
            _session = [[FBSession sessionForApplication:kApiKey getSessionProxy:kGetSessionProxy
                                                delegate:self] retain];
        } else {
            _session = [[FBSession sessionForApplication:kApiKey secret:kAppSecret delegate:self] retain];
        }
    }
    return self;
}

接下來要實作三個方法,

///////////////////////////////////////////////////////////////////////////////////////////////////
// FBSessionDelegate

- (void)session:(FBSession*)session didLogin:(FBUID)uid { 
    NSLog(@"User with id %lld logged in.", uid);
    _fpost.hidden =NO;
}


- (void)sessionDidLogout:(FBSession*)session{
    _fpost.hidden =YES;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////

-(IBAction)post_to_facebook:(id)sender{    
    
    FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
    dialog.delegate = self;
    dialog.userMessagePrompt = @"please say something!!";
    dialog.attachment = [NSString stringWithFormat:@"{\"name\":\"%@\",\"href\":\"%@\",\"caption\":\"%@\",\"description\":\"%@\",\"media\":[{\"type\":\"image\",\"src\":\"file://facebooktest/fbtry.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}",postmessage,appurl,postcaption,postdescription];
    [dialog show];
}
關於dialog.attachment,就是要post到facebook上wall的部份,可以看http://developers.facebook.com/docs/guides/attachments,裡面有細部的講解。
這樣子code的部份大概完成了,下一篇要設定一下nib file。



沒有留言:

張貼留言