使用NSOperationQueue取消Swift中的异步操作

时间:2016-03-03 23:59:29

标签: ios swift nsoperationqueue

我有一个使用NSURLSessionDelegate类(MySession)的函数,它获取重定向URL并使用NSURLSessionTask检查它的状态代码。当用户离开当前ViewController时,我的总体目标是停止任何正在进行的操作。我是否通过以下代码正确地做到了这一点?我知道你无法取消正在进行的NSOperation,但是这段代码似乎并没有像我想要的那样正确取消新的操作。

 var newQueue = NSOperationQueue()
    var operation = NSBlockOperation()

    }

    override func viewDidDisappear(animated: Bool) {

        newQueue.cancelAllOperations()

    }


    func myFunction {

        for item in myArray{


            if let urlAsString = item.url.description as? String {


                operation = NSBlockOperation(block: {

                    if self.operation.cancelled {return}

                    MySession.getDataFromServerWithSuccess(urlAsString, noRedirect: false) { result in


                        switch result {
                        case .Success:

                            if self.operation.cancelled {return}


                            //Customizing Request
                            let request = NSMutableURLRequest(
                                URL: pin.url,
                                cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
                                timeoutInterval: 5.0)
                            request.HTTPMethod = "GET"

                            var statusCode = Int()

                            let session = NSURLSession.sharedSession()
                            let task = session.dataTaskWithRequest(request) {urlData, response, responseError in

                                if self.operation.cancelled {return}

                                if let httpResponse = response as? NSHTTPURLResponse {

                                    statusCode = httpResponse.statusCode

                                    switch statusCode {
                                    case  _ where statusCode < 500 && statusCode > 299:

                                    default:
                                        break;
                                    }

                                }

                                guard responseError == nil else {
                                    print("Error during GET request on redirect: \(responseError)")
                                    return
                                }
                            }
                            task.resume()
                            self.pinsThatHaveBeenChecked.append(pin)
                            dispatch_async(dispatch_get_main_queue(),{

                                self.collectionView?.reloadData()


                            })

                        case let .Failure(error):

                            if self.operation.cancelled {return}

                            print("Error with \(pin.descriptionText): \(error)")


                        case let .NoResponse:

                            if self.operation.cancelled {return}
                            print("No response for \(pin.descriptionText) \(pin.identifier)")
                                                default: break


                        }


                    }
                })

                operation.qualityOfService  = .Background
                newQueue.addOperation(operation)

            }

            dispatch_async(dispatch_get_main_queue(),{

                self.collectionView?.reloadData()

            })


        }

0 个答案:

没有答案