iOS Facebook native login (without Facebook SDK)

落爺英雄遲暮 提交于 2019-12-04 06:48:10

You should take a look at Facebook docs here (there's a simple login example):

https://developers.facebook.com/docs/ios/ios-sdk-tutorial/authenticate/

In my opinion, I would use the Facebook SDK to perform the login, you can do something like this:

/* Constants */
#define K_FACEBOOK_REQUEST_CREDENTIALSURL @"me/?fields=id,location,name,username,bio,picture,gender,website,birthday,email"
#define K_FACEBOOK_PERMISSIONS @[@"user_about_me",@"user_birthday",@"email"]

/* Facebook Keys */
#define K_FACEBOOK_REQUEST_ID @"id"
#define K_FACEBOOK_REQUEST_USERNAME @"username"
#define K_FACEBOOK_REQUEST_LOCATION @"location"
#define K_FACEBOOK_REQUEST_FULLNAME @"name"
#define K_FACEBOOK_REQUEST_BIO @"bio"
#define K_FACEBOOK_REQUEST_WEBSITE @"website"
#define K_FACEBOOK_REQUEST_EMAIL @"email"
#define K_FACEBOOK_REQUEST_BIRTHDAY @"birthday"
#define K_FACEBOOK_REQUEST_GENDER @"gender"

- (void)initWithLoginFacebook
{
  [PFFacebookUtils logInWithPermissions:K_FACEBOOK_PERMISSIONS block:^(PFUser *user, NSError *error) {
    if (!user) {
        if (!error) 
          NSLog("ERROR_CAUSE_AUTH_USERCANCELLED");
        else 
          NSLog("ERROR_CAUSE_AUTH_FAILEDLOGIN");
    } else if (user.isNew) {
        FBRequest *request = [FBRequest requestForMe];
        [request startWithCompletionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
            if (error) 
              NSLog("ERROR_CAUSE_AUTH_FAILEDLOGIN");
            else 
              [self requestLoginFacebook:result];
        }];
    } else
        NSLog("User logged and not new!");
  }];
}

- (void)requestLoginFacebook:(id)result
 {
    NSDictionary *userData = (NSDictionary *)result;
    // Do something with the data... For example
    NSString *facebookId = userData[K_FACEBOOK_REQUEST_ID];
    NSString *name = userData[K_FACEBOOK_REQUEST_FULLNAME];
    NSString *username = [userData[K_FACEBOOK_REQUEST_USERNAME] lowercaseString];
    NSString *bio = userData[K_FACEBOOK_REQUEST_BIO];
    NSString *website = userData[K_FACEBOOK_REQUEST_WEBSITE];
    NSString *location = userData[K_FACEBOOK_REQUEST_LOCATION][@"name"];
    NSString *gender = userData[K_FACEBOOK_REQUEST_GENDER];
    NSString *birthday = userData[K_FACEBOOK_REQUEST_BIRTHDAY];
    NSString *email = userData[K_FACEBOOK_REQUEST_EMAIL];
    NSString *profileImage = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?width=180&height=180",userData[@"id"]];

}

You have to configure the Facebook SDK in the appDelegate and in the .plist file.

Your code only will work fine if the user has a Facebook account set in the device Settings.

I.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!