取消NSOperationsQueue

时间:2016-09-12 19:48:33

标签: ios swift nsoperation

我正在尝试取消我的NSOperationsQueue并从队列中删除所有操作。我打电话给方法" cancelAllOperations()"但这并没有从队列中删除操作,我知道这个方法只为操作添加了一个标志。

如何从队列中删除所有操作?或者阻止操作队列执行具有标志的操作?

private let mediaDownloadOperationQueue: NSOperationQueue = {
    let queue = NSOperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.qualityOfService = .Background

    return queue
}()

func startDownloadProcess() {
    guard downloadSwitchState == true else { return }

    let context = DataBaseManager.sharedInstance.mainManagedObjectContext
    let mediasToDownload = self.listOfMediaToDownload(context)

    for media in mediasToDownload {
        downloadMedia(media)
    }
}

private func downloadMedia(media: Media) {
    //check if operation already exist
    for operation in mediaDownloadOperationQueue.operations {
        let operation = operation as! MediaDownloadOperation

        if operation.media.objectID == media.objectID { return }
    }

    //HERE I am adding the operation to queue
    mediaDownloadOperationQueue.addOperation(MediaDownloadOperation(media: media))
}

//编辑:这是我的MediasDownloadOperation

import Foundation
import Alamofire

class MediaDownloadOperation: BaseAsyncOperation {

    let media: Media
    init(media: Media) {
        self.media = media
        super.init()
    }

    override func main() {
        guard let mediaSourceURI = media.sourceURI
        else {
            self.completeOperation()
            return
        }   

        var filePath: NSURL?
        let destination: (NSURL, NSHTTPURLResponse) -> (NSURL) = {
            (temporaryURL, response) in

            if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first, let suggestedFilename = response.suggestedFilename {
                filePath = directoryURL.URLByAppendingPathComponent("\(suggestedFilename)")
                return filePath!
            }
        return temporaryURL
    }

        RequestManager.sharedAlamofireManager.download(.GET, mediaSourceURI, destination: destination).response {
            (request, response, data, error) -> Void in

            if let filePath = filePath where error == nil {
                let saveToCameraRoll = self.media.saveToCameraRoll?.boolValue == true

                self.media.fileLocation = filePath.lastPathComponent
                self.media.saveToCameraRoll = false

                DataBaseManager.sharedInstance.save()

                if saveToCameraRoll {
                    self.media.saveMediaToCameraRoll(nil)
                }
            }

            self.completeOperation()
            NSNotificationCenter.defaultCenter().postNotificationName(MediaDownloadManager.MediaIsDownloadedNote, object: nil)

        }
    }
}

1 个答案:

答案 0 :(得分:0)

添加条件以进行测试以查看操作是否已取消似乎解决了问题:

    RequestManager.sharedAlamofireManager.download(.GET, mediaSourceURI, destination: destination).response {
        (request, response, data, error) -> Void in

        //Only download if logged in
        if (self.cancelled == false){
            print("RAN operation!")
            if let filePath = filePath where error == nil {
                let saveToCameraRoll = self.media.saveToCameraRoll?.boolValue == true

                self.media.fileLocation = filePath.lastPathComponent
                self.media.saveToCameraRoll = false

                DataBaseManager.sharedInstance.save()

                if saveToCameraRoll {
                    self.media.saveMediaToCameraRoll(nil)
                }
            }

            self.completeOperation()

            NSNotificationCenter.defaultCenter().postNotificationName(MediaDownloadManager.MediaIsDownloadedNote, object: nil)
        }else{
            print("did not run operation!  was cancelled!")
            self.completeOperation()
        }
    }