【发布时间】:2023-03-09 03:30:01
【问题描述】:
我对原生 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_id 和phone_nr)但我不能alert 和user_id...但是当我NSLog 它时,它工作得很好。问题是我不能在函数之外的任何地方使用user_id 变量。
UIAlertView 看起来像这样:
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Headline"
message:user_id
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
【问题讨论】:
-
我希望你已经调用了[alert show]?
-
来自文档:
dataTaskWithURL:completionHandler:为指定的 URL 创建一个 HTTP GET 请求,然后在完成时调用一个处理程序。 -
user_id = @"%@",[json objectForKey:@"user_id"];是一个“逗号表达式”。在初学者的 C 书籍中查找逗号表达式是什么。我敢打赌你不想在这里使用一个。
标签: ios objective-c nsstring nsdictionary nsurlsession