gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:00:50 24 4
gpt4 key购买 nike

我是 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];
}

}
}
}];
}

@结束

最佳答案

终于,我成功了:) 这是代码,可能对像我这样的初学者有帮助。虽然代码没有优化,但它可以帮助人们理解基本功能。我正在发布完整代码,其中包括自定义 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是这样的

响应 JSON={"rqBody":{"firstName":"Kunal","lastName":"Kumar","emailID":"abcd@efgh.com","userId":"1234567890"}}

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com