Posting facebook user data to server using JSON

361 views Asked by At

I am a beginner in ios programming. I am integrating fb authentication for my app. I can successfully logged-in and get the user data on console using NSlog. Now, I want to send the user data like name, email-id etc to the server using json. I searched alot and get this post but i didn't get it. Any sample code example will be great according to my code. This is what i tried. I am able to hit my server with null value. Please guide me, how can i send the parameter like first_name, last_name to the server.

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

        }
    }
}];
}

@end

1

There are 1 answers

0
Kunal Kumar On BEST ANSWER

Finally, i made it working :) Here is the code, which may help some beginners like me. Although the code is not optimized, but it can help someone understand basic functionality. I am posting full code which include custom facebook login button, fetching fb user data, and posting this data on the server using nested 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];
            }

        }
    }
}];

posted json would be like this

Response JSON={"rqBody":{"firstName":"Kunal","lastName":"Kumar","emailID":"[email protected]","userId":"1234567890"}}