2

我正在尝试从网站下载图像并将其另存为 UIImage 但如果用户的连接速度较低,这可能需要很长时间......我如何在后台下载它以便用户可以同时继续使用该应用程序?

这是代码:

theIcon.image = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://myWebsite.com/Icon.png"]]];
4

4 回答 4

1

使用 GCD。

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
    // do my background code
    dispatch_async(dispatch_get_main_queue(), ^{
        // do handling on main thread when done!
    });
});
于 2013-07-17T19:45:03.450 回答
1

使用AFNetworking

[imageView setImageWithURL:
                       [NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] 
                       placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];
于 2013-07-17T20:20:30.823 回答
0

您可以在主前台线程运行时在后台线程中执行选择器。

 [self performSelectorInBackground:@selector(downloadFile) withObject:nil];

 - (void) downloadFile {
   //download file 
   //you can show UIAlertView when done
    }

在您的 - (void) downloadFile 中,您可以下载这个大文件。并显示(或不显示)活动指示器。您可以让活动指示器变为不隐藏或隐藏,并让它 startAnimating 和 stopAnimating 将使其旋转和停止。这可以从前台和后台进程中引用。

于 2013-07-17T19:40:15.040 回答
0

快速而肮脏的方式:

NSMutableRequest* request = ... ;
[NSURLConnection sendAsynchronousRequest:request 
                                   queue:[NSOperationQueue mainQueue] 
                       completionHandler:^(NSURLResponse* response, NSData* data, NSError* error) {
    if (!error) {
        // do something with the response data.    
    }
}];

这种方法足以用于“概念验证”、具有简单不安全连接的玩具程序、Apple 示例,以及为娱乐而学习 iOS 的爱好者以及展示反模式的示例(“你应该怎么做,不!”) .

如果您想要一个可靠的方法,您需要NSURLConnection在异步模式下使用并实现委托 - 或使用第三方库。;)

于 2013-07-17T22:11:08.533 回答