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

How do make background task complete when that view has been popped from the navigation stack

_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 已被弃用,我最终会解决这个问题。

想必_queue是view controller的成员变量吧?如果是这样,那么作为让事情最初正常工作的快速修复,您可以将其更改为静态成员变量(以更改其生命周期),但最好将其移动到模型 class 并拥有模型代表您的视图控制器上传图像
这导致了更好的设计,尤其是一旦它变成异步的——想象一下这个场景:

- 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