ios - 使用 JSON 将 Facebook 用户数据发布到服务器

标签 ios objective-c json facebook webservice-client

我是ios编程的初学者。我正在为我的应用程序集成 Facebook 身份验证。我可以使用 NSlog 成功登录并在控制台上获取用户数据。现在,我想使用 json 将用户数据(如姓名、电子邮件 ID 等)发送到服务器。我搜索了很多,get this post 但我没明白。根据我的代码,任何示例代码示例都会很棒。这就是我尝试过的。我能够用空值访问我的服务器。请指导我,如何将first_name、last_name等参数发送到服务器。

(IBAction)btnFacebookPressed:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
        // Process error
    } else if (result.isCancelled) {
        // Handle cancellations
    } else {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if ([result.grantedPermissions containsObject:@"email"])
        {
            // Do work
            if ([FBSDKAccessToken currentAccessToken])
            {

                [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, first_name, last_name, email"}]

                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
                {

                     if (!error)
                     {
                         NSDictionary *userData = (NSDictionary *)result;
                         NSString *facebookID = userData[@"id"];
                         NSString *userName = userData[@"name"];
                         NSString *firstName = userData[@"first_name"];
                         NSString *lastName = userData[@"last_name"];
                         NSString *emailid = userData[@"email"];

                         NSLog(@"user data:%@", userData);

                         //NSLog(@"fetched user:%@", result);


                         NSMutableURLRequest *request = [NSMutableURLRequest
                                                         requestWithURL:[NSURL URLWithString:@"http:xxxxxxxxxxxxx"]];

                         NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:facebookID,@"userId", firstName,@"firstName", lastName,@"lastName",emailid,@"emailId", nil];

                         NSLog(@"requested json data is: %@", requestData);

                         NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:0 error:&error];
                         NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];
                        [request setHTTPMethod:@"POST"];
                        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                        [request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
                        [request setHTTPBody:postData];

                         NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

                         NSError *error = [[NSError alloc] init];
                         NSHTTPURLResponse *response = nil;
                         NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                         NSLog(@"Response code: %ld", (long)[response statusCode]);


                     }
                 }];
            }





            {
            [self performSegueWithIdentifier:@"loginSuccess" sender:self];
            }

        }
    }
}];
}

@结束

最佳答案

最后,我让它工作了:)这是代码,这可能会帮助像我这样的初学者。虽然代码没有优化,但它可以帮助人们理解基本功能。我发布了完整的代码,其中包括自定义 Facebook 登录按钮、获取 Facebook 用户数据以及使用嵌套 json 将这些数据发布到服务器上。

- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)didReceiveMemoryWarning 
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.

}
-(IBAction)btnFacebookPressed:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
    if (error) {
        // Process error
    } else if (result.isCancelled) {
        // Handle cancellations
    } else {
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if ([result.grantedPermissions containsObject:@"email"])

{
            if ([FBSDKAccessToken currentAccessToken])
            {

[[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"id, name, first_name, last_name, email"}]

                 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
                {

                     if (!error)
                     {
                         NSDictionary *userData = (NSDictionary *)result;
                         NSString *facebookID = userData[@"id"];
                         NSString *userName = userData[@"name"];
                         NSString *firstName = userData[@"first_name"];
                         NSString *lastName = userData[@"last_name"];
                         NSString *emailid = userData[@"email"];

                         NSLog(@"user data:%@", userData);
                         NSMutableURLRequest *request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://xxxxxxxxxxxxxxx(your connection url)"]];
                         NSDictionary *newDataInfo =[NSDictionary dictionaryWithObjectsAndKeys:facebookID,@"userId", firstName,@"firstName", lastName,@"lastName",emailid,@"emailID",nil];

                         NSDictionary *requestData = [[NSDictionary alloc] initWithObjectsAndKeys:newDataInfo,@"rqBody", nil];



                         NSData *postData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];

                         NSDictionary *json = [NSJSONSerialization JSONObjectWithData:postData
                                                                              options:kNilOptions
                                                                                error:&error];
                         NSString *jsonString = [[NSString alloc] initWithData:postData
                                                                      encoding:NSUTF8StringEncoding];
                         NSLog(@"Response JSON=%@", jsonString);



                         NSString *postLength = [NSString stringWithFormat:@"%lu", (unsigned long)[postData length]];

                        [request setHTTPMethod:@"POST"];
                        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
                         [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
                        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
                        //[request setValue:@"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
                        [request setHTTPBody:postData];

                         NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

                         NSError *error = [[NSError alloc] init];
                         NSHTTPURLResponse *response = nil;
                         NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
                         NSLog(@"Response code: %ld", (long)[response statusCode]);
 }
                 }];
            }

            {
                [self performSegueWithIdentifier:@"loginSuccess" sender:self];
            }

        }
    }
}];

发布的 json 会是这样的

Response JSON={"rqBody":{"firstName":"Kunal","lastName":"Kumar","emailID":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a9c8cbcacde9cccfcec187cac6c4" rel="noreferrer noopener nofollow">[email protected]</a>","userId":"1234567890"}}

关于ios - 使用 JSON 将 Facebook 用户数据发布到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30750704/

相关文章:

ios - 有没有办法解决 Apple 的 UITextField Emoji 错误?

ios - Xcode 10 生成的 Assets.car 比 Xcode 9 大?

ios - ld : library not found for -lVuforia

ios - RestKit .20 RKRequestDescriptor postObject - (400-499) 中的预期状态代码,得到 200

ios - 我怎么知道iBeacons的纬度(X)和经度(Y)位置

javascript - node.js 请求 POST 数组 "first argument must be string or buffer"

ios - 如何获取 NSFetchedResultsController Swift 部分中的对象数

ios - MKDirections 计算ETAWithCompletionHandler : in background state

java - Gson 转换为具有两种日期格式的 Json 不起作用

javascript - nestableSortable 与 Nestable JS 库