0

_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

而不是使用'NSURLConnection'发送同步请求尝试'NSURLSessi on'与异步请求。同步请求会阻止它的线程。会话很容易使用,不会阻塞线程,并为您保留执行队列。 – clemens

回答

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 
+1

您应该避免使用静态变量,特别是同步请求。 – clemens

+0

非常感谢,现在声明它是静态工作的。我最终将把它移到一个模型类。 –

+4

@macmoonshine,我说“作为一个快速修复”。即不是长期解决方案。 – Gruntcakes

相关问题