我在我的 iOS 应用程序中设置了一个简单的 Objective-C 类,它有一个简单的任务,即下载一个 JSON 文件,解析它,然后传回一个 NSString,其中包含一个从下载的 JSON 文件解析的变量。
我遇到的问题是我从另一个类调用这个类,这一切都很好,但是我需要将 NSString 传回我调用它的类。
问题是该方法在 connectionDidFinishLoading 发生之前传回空的 NSString ....因此 NSString 永远不会被分配一个字符串......
我在我的方法中设置了一个 while 循环,但它并没有真正起作用......
这是我的代码:
-(NSString *)get_user_icon:(NSString *)YT_ID {
// Set BOOL to 0 for initial setup.
icon_check = 0;
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
dispatch_queue_t downloadQueue = dispatch_queue_create("Icon downloader YouTube", NULL);
dispatch_async(downloadQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLConnection *theConnection_YT = [[NSURLConnection alloc] initWithRequest:theRequest_YT delegate:self];
if (theConnection_YT) {
YT_JSON_FEED = [[NSMutableData alloc] init];
NSLog(@"Respoce happening...");
}
else {
NSLog(@"failed");
}
});
});
while (icon_check == 0) {
NSLog(@"Wait");
}
return icon_url;
}
/// Data loading ///
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[YT_JSON_FEED setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[YT_JSON_FEED appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSString *msg = [NSString stringWithFormat:@"Failed: %@", [error description]];
NSLog(@"%@",msg);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *myError = nil;
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:YT_JSON_FEED options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:@"items"] valueForKey:@"snippet"] valueForKey:@"thumbnails"] valueForKey:@"default"] valueForKey:@"url"];
icon_check = 1;
}
最佳答案
对于同步请求(阻塞直到有东西返回),使用 NSURLConnection
的 sendSynchronousRequest:returningResponse:error:
代替。像这样:
-(NSString *)get_user_icon:(NSString *)YT_ID {
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:theRequest_YT returningResponse:&response error:&error];
//Check response and error for possible errors here.
//If no errors.
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:@"items"] valueForKey:@"snippet"] valueForKey:@"thumbnails"] valueForKey:@"default"] valueForKey:@"url"];
return icon_url;
}
但是不推荐这样做。您需要将 API 更改为异步的。基于委托(delegate),但更优选地,使用基于 block 的 API。
关于ios - 如何检查 connectionDidFinishLoading 何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21942654/