使用 JSON 将 Facebook 用户数据发布到服务器
Posting facebook user data to server using JSON
我是 ios 编程的初学者。我正在为我的应用程序集成 fb 身份验证。我可以使用 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];
}
}
}
}];
}
@end
终于,我成功了:)这是代码,可能对像我这样的初学者有所帮助。虽然代码没有优化,但它可以帮助人们理解基本功能。我正在发布完整代码,其中包括自定义 facebook 登录按钮、获取 fb 用户数据以及使用嵌套 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":"abcd@efgh.com","userId":"1234567890"}}
我是 ios 编程的初学者。我正在为我的应用程序集成 fb 身份验证。我可以使用 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];
}
}
}
}];
}
@end
终于,我成功了:)这是代码,可能对像我这样的初学者有所帮助。虽然代码没有优化,但它可以帮助人们理解基本功能。我正在发布完整代码,其中包括自定义 facebook 登录按钮、获取 fb 用户数据以及使用嵌套 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":"abcd@efgh.com","userId":"1234567890"}}