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

相關問題