Search code examples
iphoneiosfacebookfacebook-ios-sdk

FB Singleton Login


I'm creating a singleton to access all Facebook methods and I want to handle the Login dialog in this singleton.

I followed the iOS SDK Tutorial on Facebook, but it only allows me to login within application launch and not when a user presses a button.

Whats the alternative to

- (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];
}

It seems to be the problem, my App isn't switching to the browser or FB App to login. When I'm implementing the same stuff in AppDelegate it works, but immediatly after Application launch.


Solution

  • I have solved it like this:

    in AppDelegate:

    -(void)connectToFacebook{
    facebook = [[Facebook alloc] initWithAppId:kAPPID andDelegate:self];
    
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"] 
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    
    }
    
    if (![facebook isSessionValid]) {
        [facebook authorize:nil];
    }
    }
    
    // For 4.2+ support
    - (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
    sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url]; 
    }
    
    - (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];
    }
    

    And in Singleton:

    - (id)init {
    self = [super init];
    if (self != nil) {
        NBNAppDelegate *delegate = (NBNAppDelegate *)[[UIApplication sharedApplication] delegate];
        [delegate connectToFacebook];
        facebook =  delegate.facebook;        
    }
    return self;
    }