当从导航堆栈弹出该视图时,如何使后台任务完成

时间:2016-11-17 18:39:36

标签: ios objective-c image-uploading background-process nsoperationqueue

_queue是一个NSOperationQueue对象。我使用以下内容将图像上传到服务器:

[_queue addOperationWithBlock:^{
  //POST request used to upload photo to server
  //request has already been successfully configured before this step
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
}];

这可能需要几秒钟,如果我按导航控制器上的后退按钮,连接将关闭,并且图像将不会上传。即使从导航堆栈弹出视图控制器,如何才能进行此后台任务?

我知道sendSynchronousRequest已被弃用,我最终会解决这个问题。

1 个答案:

答案 0 :(得分:1)

大概_queue是视图控制器的成员变量?如果是这样,那么作为最初工作的快速修复,您可以将其更改为静态成员变量(以更改其生命周期),但将它移动到模型类并让模型上传图像会更好代表您的视图控制器
这导致了更好的设计,特别是一旦它变得异步 - 想象一下这个场景:

- view controller A starts the upload
- user navigates to view controller B
- upload fails and you need to notify the user of the failure or retry the upload
- now what? A started the upload but it no longer exists how do you notify the user or retry the upload?

如果你让模特有责任上传图片,那就是这种情况:

- view controller A starts the upload
- user navigates to view controller B
- upload fails and you need to notify the user or retry
- model broadcasts a notification the upload has failed or just retires the upload
- a meta view controller listens for the notification and displays a dialog to the user informing of the failure