[英]How to start and stop background thread iOS
我正在開發一個iPhone應用程序,其中,我要啟動后台線程以從服務器下載圖像。 在下載圖像時,如果用戶要取消下載,則單擊按鈕時他可以取消下載,這意味着我想停止執行后台線程。
有可能嗎? 在iPhone中
您可以使用此代碼開始繼續進行后台下載。
taskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
}];
//code to download .
[[UIApplication sharedApplication] endBackgroundTask:taskId];
你可以打電話
[[UIApplication sharedApplication] endBackgroundTask:taskId];
停止后台任務。
但是此下載將僅持續幾分鍾。 然后,如果繼續下載,該應用將崩潰。
如果要在后台執行操作,則需要將其包裝在后台任務中。 完成后調用endBackgroundTask
也很重要-否則應用程序將在其分配的時間到期后被終止。
這樣的事情應該為您工作:
聲明財產:
@property(assign, nonatomic) UIBackgroundTaskIdentifier backgroundFetchTask;
然后:
- (void) fetchImageInBackground
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self beginBackgroundFetchTask];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
// Store your image
[self endBackgroundFetchTask];
});
}
- (void) beginBackgroundFetchTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundFetchTask];
}];
}
- (void) endBackgroundFetchTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundFetchTask = UIBackgroundTaskInvalid;
}
您可以將AFNetworking用於此目的。 https://github.com/AFNetworking/AFNetworking
AFImageRequestOperation正是這樣做的。
下載圖片的示例:
AFImageRequestOperation * _operation = [AFImageRequestOperation imageRequestOperationWithRequest:request success:^(UIImage *image) {
// image is your image
_operation = nil;
}];
[_operation start];
取消線程的示例:
[_operation cancel];
因此,在您的情況下->聲明變量AFImageRequestOperation * _operation; 在@interface或@implementation中,並使用它在后台下載圖像。
我會做一個singlton類MyImageBackgrounfDownloader
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.