gpt4 book ai didi

ios - NSDictionary 到 NSString 不工作

转载 作者:行者123 更新时间:2023-11-28 22:13:13 25 4
gpt4 key购买 nike

我对 native iOS 编程完全陌生,对此有一些大大小小的问题。我的问题之一如下:

我想从服务器检索一个user_id,所以我使用NSURLSession。我的代码看起来像这样:

NSString *phone_nr = @"00436604056720";
__block NSString *user_id;

NSURLSession *session_json = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session_json dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/picshare/index.php?phone_nr=%@", phone_nr]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);

user_id = @"%@",[json objectForKey:@"user_id"];
}];

[dataTask resume];

代码工作正常(我检索到正确的 user_idphone_nr)但是我不能alert user_id... 但是当我 NSLog 它时,它工作得很好。问题是我不能在函数之外的任何地方使用 user_id 变量。

UIAlertView 看起来像这样:

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Headline"
message:user_id
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];

最佳答案

NSString *phone_nr = @"00436604056720";

NSURLSession *session_json = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session_json dataTaskWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://localhost/picshare/index.php?phone_nr=%@", phone_nr]] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@", json);

NSString *user_id = [json objectForKey:@"user_id"];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Headline"
message:user_id
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
});
}];

[dataTask resume];

不要声明 _block 变量。

关于ios - NSDictionary 到 NSString 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22378542/

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