从url转换为uiimage时暂停

时间:2012-03-11 08:30:55

标签: ios uiimageview uiimage nsdata nsurl

我有一个应用程序,我下载图像。我是这样做的:

NSString *imgURL = [@"http://www.kwikspik.com/static/" stringByAppendingString:spikFromTopic.user_image];
        NSData *imgData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imgURL]];
        UIImage *image = [[UIImage alloc] initWithData:imgData];
        UIImageView *userImage =[[UIImageView alloc] initWithFrame:CGRectMake(20,size,userImageSize,userImageSize)];
        userImage.image = image;

这段代码实现了很长时间。

互联网连接有问题吗?或者也许在我的代码中?

1 个答案:

答案 0 :(得分:0)

您正在进行同步调用以获取图像数据。这意味着在此期间你的主线程(UI线程)将保持阻塞(假设这不是从线程调用的,我假设不是因为你在这里更新UI应该总是在主UI线程中。它本质上意味着你不能在调用返回之前做任何事情。您可以使用异步(非阻塞方式来执行此操作。使用Grand Central Dispatch(GCD)的一个示例

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),  ^{        
// This runs in background               

NSData *imgData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString:imgURL]];
        UIImage *image = [[UIImage alloc] initWithData:imgData];               


      dispatch_async(dispatch_get_main_queue(), ^{                        
             //This block runs on main thread, so update UI
            UIImageView *userImage =[[UIImageView alloc] initWithFrame:CGRectMake(20,size,userImageSize,userImageSize)];
        userImage.image = image;
            });    
    });

或者在NSURLConnection中查看像sendAsynchronousRequest:queue:completionHandler这样的API

相关问题