我在iOS應用程序中設置了一個簡單的Objective-C類,它有一個簡單的任務,下載一個JSON文件,解析它,然後傳回一個NSString,其中包含一個從下載的JSON文件。如何檢查connectionDidFinishLoading何時完成
我的問題是,我從另一個類調用這個類,這一切都很好,但是我需要將NSString傳回給我從中調用它的類。
的問題是,該方法傳回空的NSString BEFORE connectionDidFinishLoading發生....等等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;
}
請勿「檢查」。設置你的委託,當下載結束時你將被TOLD。 – matt