如何检查connectionDidFinishLoading何时完成

时间:2014-02-21 18:43:37

标签: ios objective-c json class while-loop

我在我的iOS应用程序中设置了一个简单的Objective-C类,它有一个简单的任务,下载一个JSON文件,解析它然后传回一个NSString,其中包含从下载的JSON文件解析的变量。

我遇到的问题是我从另一个类调用这个类,这一切都很好但是我需要将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;
}

1 个答案:

答案 0 :(得分:2)

对于同步请求(阻止直到有东西要返回),请改用NSURLConnection的{​​{1}}。像这样:

sendSynchronousRequest:returningResponse:error:

但不建议这样做。您需要将API更改为异步。基于委托,但更优选地,使用基于块的API。