在后台运行代码

时间:2013-07-17 19:36:39

标签: ios objective-c download background-process

我正在尝试从网站下载图像并将其保存为UIImage但如果用户连接不足,则可能需要永久...我如何在后台下载它以便用户可以继续使用该应用程序在此期间?

这是代码:

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

4 个答案:

答案 0 :(得分: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!
    });
});

答案 1 :(得分:1)

使用AFNetworking

[imageView setImageWithURL:
                       [NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] 
                       placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]];

答案 2 :(得分:0)

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

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

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

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

答案 3 :(得分: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并实现委托 - 或使用第三方库。 ;)

相关问题