2012年6月30日 星期六

FaceBook - post article & photo on the wall

首先
當然是要加上FB的SDK

然後在.h檔設定如下

#import "FBConnect.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate,FBDialogDelegate, FBSessionDelegate, FBLoginDialogDelegate,FBRequestDelegate>
{
}

// Facebook 
@property (nonatomic, retain) Facebook *facebook;
接下來到.m檔 MyAppId是自己在FaceBook申請的應用程式id
-(void)initFacebook
{
    // 初始化facebook
    facebook = [[Facebook alloc] initWithAppId:MyAppId andDelegate:self];
    
    // 記錄facebook登入的token
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] && [defaults objectForKey:@"FBExpirationDateKey"]) 
    {
        facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }
}
接下來修改AppDelegate的三個函式
-(void)applicationDidBecomeActive:(UIApplication *)application
{  
    [self extendAccessTokenIfNeeded];
}

-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url 
{
    [self handleOpenURL:url];
    return NO;
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation 
{
    [self handleOpenURL:url];
    return NO;
}
補上其中呼叫的兩個函式handleOpenURL跟extendAccessTokenIfNeeded
-(void)extendAccessTokenIfNeeded
{
    [[self facebook] extendAccessTokenIfNeeded]; 
}

-(BOOL)handleOpenURL:(NSURL *)url
{
    return [self.facebook handleOpenURL:url];
}
取得授權跟login
-(void)loginFacebook
{
    if(![facebook isSessionValid])
    {
        //取得相關授權
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"user_likes",
                                @"read_stream",
                                @"user_birthday",
                                @"publish_stream",
                                @"offline_access",
                                @"user_status",
                                nil];
        [self.facebook authorize:permissions];
    }
    else
    {
        [self fbDidLogin];
    }
}
login跟logout的內容
- (void)fbDidLogin 
{
    NSLog(@"fbDidLogin");
    [self storeAuthData:[[self facebook] accessToken] expiresAt:[[self facebook] expirationDate]];
}

- (void)fbDidLogout 
{
    NSLog(@"fbDidLogout");
    
    // Remove saved authorization information if it exists and it is
    // ok to clear it (logout, session invalid, app unauthorized)
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"FBAccessTokenKey"];
    [defaults removeObjectForKey:@"FBExpirationDateKey"];
    [defaults synchronize];
}
接下來重頭戲來了,將文章跟照片post上FB
-(void)postFacebook
{
    NSLog(@"fbDidLogin");
    [self storeAuthData:[[self facebook] accessToken] expiresAt:[[self facebook] expirationDate]];
    
    currentAPICall = kAPIGraphUserPost;
    
    NSString *sMessage = [[NSString alloc] initWithString:[NSString stringWithFormat:@"3我要潑的訊息"]];
    
        NSMutableDictionary * params2 = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         g_FBPostImage, @"picture",sMessage,@"message",
                                         nil];
    
        [facebook requestWithGraphPath:@"me/photos" 
                             andParams:params2 
                         andHttpMethod:@"POST" 
                           andDelegate:self];
}
如果不要潑圖片,只要潑訊息,可以將me/photos改成me/feed,然後g_FBPostImage, @"picture",這段拿掉即可
最後補上一些FB預設的函式,用以捕捉訊息
- (void)apiFQLIMe 
{
    // Using the "pic" picture since this currently has a maximum width of 100 pixels
    // and since the minimum profile picture size is 180 pixels wide we should be able
    // to get a 100 pixel wide version of the profile picture
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   @"SELECT uid, name, pic FROM user WHERE uid=me()", @"query",
                                   nil];
    [[self facebook] requestWithMethodName:@"fql.query"
                                 andParams:params
                             andHttpMethod:@"POST"
                               andDelegate:self];
}

- (NSDictionary *)parseURLParams:(NSString *)query {
    
 NSArray *pairs = [query componentsSeparatedByString:@"&"];
 NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
 for (NSString *pair in pairs) {
  NSArray *kv = [pair componentsSeparatedByString:@"="];
  NSString *val =
        [[kv objectAtIndex:1]
         stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        
  [params setObject:val forKey:[kv objectAtIndex:0]];
 }
    return params;
}


- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:accessToken forKey:@"FBAccessTokenKey"];
    [defaults setObject:expiresAt forKey:@"FBExpirationDateKey"];
    [defaults synchronize]; 
}

- (void)fbSessionInvalidated 
{
    NSLog(@"fbSessionInvalidated");
    
    UIAlertView *alertView = [[UIAlertView alloc]
                              initWithTitle:@"Auth Exception"
                              message:@"Your session has expired."
                              delegate:nil
                              cancelButtonTitle:@"OK"
                              otherButtonTitles:nil,
                              nil];
    [alertView show];
    [self fbDidLogout];
}


#pragma mark - FBRequestDelegate Methods
/**
 * Called when the Facebook API request has returned a response. This callback
 * gives you access to the raw response. It's called before
 * (void)request:(FBRequest *)request didLoad:(id)result,
 * which is passed the parsed response object.
 */
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response 
{
    NSLog(@"received response");
}

- (void)request:(FBRequest *)request didLoad:(id)result 
{
    NSLog(@"request:didLoad");
    
    haveFbRequest = false;
    
    if ([result isKindOfClass:[NSArray class]] && ([result count] > 0))
    {
        result = [result objectAtIndex:0];
    }
    
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"成功分享到facebook了!" message:nil delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
    
    [alertView show];
}

- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"request fail");
    NSLog(@"Error message: %@", [[error userInfo] objectForKey:@"error_msg"]);
}




#pragma mark - FBDialogDelegate Methods

/**
 * Called when a UIServer Dialog successfully return. Using this callback
 * instead of dialogDidComplete: to properly handle successful shares/sends
 * that return ID data back.
 */
- (void)dialogCompleteWithUrl:(NSURL *)url 
{
    NSLog(@"dialogCompleteWithUrl.");
    
    if (![url query]) 
    {
        NSLog(@"User canceled dialog or there was an error");
        return;
    }
    
}

沒有留言:

張貼留言