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