不能在单独的线程中调用委托方法

时间:2015-04-10 17:50:31

标签: multithreading swift nsurlconnection

我搜索过但找不到答案。

单独的主题在这里:

if let urlConnection = NSURLConnection(request: self.request, delegate: self, startImmediately: false) {

     dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.value), 0)){
     println("begin")
     let queue = NSOperationQueue()
     urlConnection.setDelegateQueue(queue)
     NSURLConnection.sendAsynchronousRequest(self.request, queue: queue) {  (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in

dispatch_async(dispatch_get_main_queue()) {
     println("then")
     if self.loadDataFinish {
         //UI code here
     }

但是在委托方法中没有任何反应:

func connectionDidFinishLoading(connection: NSURLConnection) {
    loadDataFinish = true
}

此队列是否在不调用Finish方法的情况下终止?

urlConnection是在单独的线程中创建还是在其中创建的?

setDelegateQueue没什么可帮助的?

打印“开始”,几秒钟后打印“然后”。请求完成。

什么时候单独的线程终止?

1 个答案:

答案 0 :(得分:0)

func request(baseApiRequest:BaseApiRequest,apiRequestCompletionHandler:(baseApiResponse:BaseApiResponse) -> Void){
    var start = NSDate().timeIntervalSince1970
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { ()->() in
        var httpController = HttpController()
        var baseApiResponse = BaseApiResponse()
        httpController.getHttpResponse(baseApiRequest, httpCompletionHandler: { (data) -> Void in
            if let finalData = data {
                baseApiResponse = baseApiRequest.getBaseApiResponse().mapFromJson(finalData)
                println("request data valid map to baseApiResponse")
            }
            apiRequestCompletionHandler(baseApiResponse:baseApiResponse)
            println("request deltaTime: \(NSDate().timeIntervalSince1970 - start)")
        })
    })
}



 func getHttpResponse(baseApiRequest:BaseApiRequest,httpCompletionHandler:(data:NSData!) -> Void){
    if let requestUrl = NSURL(string:baseApiRequest.httpRequestUrl()){
        let request = NSMutableURLRequest(URL: requestUrl)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPMethod = baseApiRequest.httpRequestMethodType().rawValue
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 22.22

        switch(baseApiRequest.httpRequestMethodType()){
        case BaseApiRequest.HttpRequestMethodType.Post:

            var err: NSError?
            request.HTTPBody = NSJSONSerialization.dataWithJSONObject(baseApiRequest.getHttpRequestParamsAsDictionary(),
                options: NSJSONWritingOptions.allZeros, error: &err)
        default:
            break
        }

        var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfig)

        let task = session.dataTaskWithRequest(request) {
            data, response, error in
            if let httpResponse = response as? NSHTTPURLResponse {
                if httpResponse.statusCode != 200 {
                    println("response was not 200: \(response)")
                }
                 println("response : \(response)")
            }
            if (error != nil) {
                println("error submitting request: \(error)")
            }
            httpCompletionHandler(data:data)
        }
        task.resume()
    }
}