iOS與Facebook SDK
iOS與Facebook SDK |
---|
這邊主要示範,iOS-App登入FaceBook後,取得使用者的相關資料(GraphApi)。 |
開始先在FaceBook註冊你的iOS App |
取得"應用程式ID" |
寫到應用程式.plist |
登入Facebook準備工作AppDelegate.h |
AppDelegate.m |
#import "AppDelegate.h"
@implementation AppDelegate
@synthesize window = _window, tabBarController = tabBarController_, facebook = facebook_;
#pragma mark - Facebook Delegate //登入 -(void)fbDidLogin { //記錄帳戶資訊 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:[facebook_ accessToken] forKey:@"FBAccessTokenKey"]; [defaults setObject:[facebook_ expirationDate] forKey:@"FBExpirationDateKey"]; [defaults synchronize]; } //登出 -(void)fbDidLogout { //清除帳戶資訊 NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey:@"FBAccessTokenKey"]) { [defaults removeObjectForKey:@"FBAccessTokenKey"]; [defaults removeObjectForKey:@"FBExpirationDateKey"]; [defaults synchronize]; } //退出App exit(1); } //取消登入 -(void)fbDidNotLogin:(BOOL)cancelled { if (cancelled) { exit(1); } }
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
}
-(void)fbSessionInvalidated {
}
#pragma mark - System //應用程式啟動 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window.rootViewController = tabBarController_; [self.window makeKeyAndVisible];
self.facebook = [[Facebook alloc]initWithAppId:kFBAppID andDelegate:self]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; if ([defaults objectForKey:@"FBAccessTokenKey"] &&[defaults objectForKey:@"FBExpirationDateKey"]) { self.facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"]; self.facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"]; }
if (![self.facebook isSessionValid]) { [facebook_ authorize:nil]; }else{ //取得相關授權 NSArray *permissions = [[NSArray alloc] initWithObjects: @"user_likes", @"read_stream", @"user_birthday", nil]; [self.facebook authorize:permissions]; }
return YES; }
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url { return [self.facebook handleOpenURL:url]; }
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { return [self.facebook handleOpenURL:url]; } |
rootViewController相關實作,畫面LayOut |
LoginViewController.h |
#import <UIKit/UIKit.h>
#import "Facebook.h"
@interface LoginViewController : UIViewController<FBRequestDelegate> { UIImageView *fbImageView_; UILabel *fbUserName_; UILabel *fbGender_; UILabel *fbBirthday_; } @property (strong, nonatomic)IBOutlet UIImageView *fbImageView; @property (strong, nonatomic) IBOutlet UILabel *fbUserName; @property (strong, nonatomic) IBOutlet UILabel *fbGender; @property (strong, nonatomic) IBOutlet UILabel *fbBirthday; - (IBAction)fbMyInfo:(id)sender;
@end |
LoginViewController.m |
#import "LoginViewController.h"
#import "AppDelegate.h"
@interface LoginViewController () { //應用程式的委派 AppDelegate *appDelegate_; //取得facebook的結果 NSDictionary *fbResult_; } @end
@implementation LoginViewController @synthesize fbImageView = fbImageView_; @synthesize fbUserName = fbUserName_; @synthesize fbGender = fbGender_; @synthesize fbBirthday = fbBirthday_;
#pragma mark - facebok FBRequestDelegate 請求資料後處理 -(void)requestLoading:(FBRequest *)request { //NSLog(@"%@",[request description]); }
-(void)request:(FBRequest *)request didFailWithError:(NSError *)error { NSLog(@"Fail"); }
-(void)request:(FBRequest *)request didLoad:(id)result { if ([result isKindOfClass:[NSDictionary class]]) { //暫存facebook資料 fbResult_ = [[NSDictionary alloc]initWithDictionary:result]; //使用者的照片 NSURL *url = [NSURL URLWithString:[NSString stringWithFormat: @"https://graph.facebook.com/%@/picture?type=small",[result objectForKey:@"id"]]]; NSData *imageData = [NSData dataWithContentsOfURL:url]; self.fbImageView.image = [UIImage imageWithData:imageData];
//稱呼 self.fbUserName.text = [result objectForKey:@"name"]; //性別 self.fbGender.text = ([[result objectForKey:@"gender"]isEqualToString:@"male"] ?@"男":@"女"); //計算年齡 NSDateFormatter *dateFormate = [[NSDateFormatter alloc]init]; dateFormate.dateFormat = @"MM/dd/yyyy"; NSDate *birthday = [dateFormate dateFromString:[result objectForKey:@"birthday"]]; NSTimeInterval dateDiff = [birthday timeIntervalSinceNow]; int age=trunc(dateDiff/(60*60*24))/365 *-1; self.fbBirthday.text = [NSString stringWithFormat:@"%i",age]; } } //登出 - (void)fbLogout { [appDelegate_.facebook logout]; } //瀏覽更多資訊 - (IBAction)fbMyInfo:(id)sender { NSString *myInfo = [fbResult_ objectForKey:@"link"]; [[UIApplication sharedApplication]openURL:[NSURL URLWithString:myInfo]]; } #pragma mark - system - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; }
- (void)viewDidLoad { [super viewDidLoad]; //取得應用程式的委派 appDelegate_ = (AppDelegate*)[UIApplication sharedApplication].delegate; // Do any additional setup after loading the view from its nib.
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"Logout" style:UIBarButtonItemStyleBordered target:self action:@selector(fbLogout)];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: @"name,picture,gender,link,birthday", @"fields", nil]; NSLog(@"查詢參數: %@",params); //執行facebook的查詢 [[appDelegate_ facebook] requestWithGraphPath:@"me" andParams:params andDelegate:self]; }
- (void)viewDidUnload { [self setFbUserName:nil]; [self setFbGender:nil]; [self setFbBirthday:nil]; [self setFbImageView:nil]; [super viewDidUnload]; // Release any retained subviews of the main view. // e.g. self.myOutlet = nil; }
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { return (interfaceOrientation == UIInterfaceOrientationPortrait); } @end |
Graph Api取資料 |
帶參數查詢me是一個物件,擁有這些欄位,請注意存取權限,必須經過用戶同意… |
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"name,picture,gender,link,birthday", @"fields",nil];
[[appDelegate_ facebook] requestWithGraphPath:@"me" andParams:params andDelegate:self]; |
權限設定,參考到AppDelegate.m |
if (![self.facebook isSessionValid]) {
[facebook_ authorize:nil]; }else{ //取得相關授權 NSArray *permissions = [[NSArray alloc] initWithObjects: @"user_likes", @"read_stream", @"user_birthday", nil]; [self.facebook authorize:permissions]; } |
與"me"相關的Connections,例如 |
[[appDelegate_ facebook] requestWithGraphPath:@"me/friendlists" andDelegate:self]; [[appDelegate_ facebook] requestWithGraphPath:@"me/friends" andDelegate:self]; |
Facebook API的對話框 |
//發送邀請 |
小結: |
Facebook取得資料是json格式,所以只要用NSDictionary objectForKey(Key-value),進行處理。 |