2017-08-16 112 views
0

我有一些麻煩,下面的代碼。 雖然它的工作,但有一些時間問題。session.dataTask同步問題

首先讓我說什麼,我希望,我想數據下載完成後,我的形象準備使用時,完成處理程序應該運行。但現實似乎完全不同。當我嘗試它時,完成處理程序立即被調用(我可以在控制檯中看到'All OK'),就好像一切都是即時的。但圖像實際上顯示得更晚。我錯過了什麼?

let imageURL = URL(string: myURLString) 
session = URLSession.shared, 
_ = session.dataTask(with: imageURL) {[weak self] 
    (data: Data?, response: URLResponse?, error: Error?) in 
    if error == nil { 
     print("All OK") 
     self?.theImage = UIImage(data: data!) 
     self?.theView.image = self?.theImage 
    } else {print(error!)} 

    DispatchQueue.main.async { 
     self?.activityIndicator.stopAnimating() 
     self?.theView.setNeedsDisplay() 
    } 
    }.resume() 
+0

當數據從服務器加載並可用時,處理程序將再次被調用。你還應該在最後一個大括號之前添加session.finishTasksAndInvalidate().resume() –

+0

好的。 「處理程序會再次被調用」是什麼意思?它已被調用。應該被稱爲多次? – Michel

+0

當數據被提取時,控件再次到達處理程序。另外,self?.theView.image = self?.Image應該在主線程上。你使用的是哪個版本的swift? –

回答

1

你可以試試這段代碼嗎?

控制不應實際往裏走在第一次調用處理程序。我認爲有代碼中的一些錯誤,以及我剛纔所指出的,尤其是在主線程需要更新UI

let session : URLSession 
    let config = URLSessionConfiguration.default 
    var resultFromServer: Any? 
    let responseResultData = [String:Any]() 
    session = URLSession(configuration: config, delegate: nil, delegateQueue: nil) 
    session.dataTask(with: request) { (data, response, error) in 

     if error != nil { 

      DispatchQueue.main.async(execute: { 

       session.invalidateAndCancel() 

      }) 

     }else{ 

      let httpResponse: HTTPURLResponse = response as! HTTPURLResponse 

       do{ 

        resultFromServer = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        if httpResponse.statusCode == 200 || httpResponse.statusCode == 201 || httpResponse.statusCode == 202 || httpResponse.statusCode == 204 || httpResponse.statusCode == 203 { 

         if let respArr = resultFromServer as? [Any]{ 

          //resp is array 


         }else if let respdict = resultFromServer as? [String : Any] { 

          //resp is dict 


         }else{ 

          //resp is something else maybe string, etc 

         } 

        } 
        else { 


         //error status code something like 500, 404, etc 

        } 


       } 

       catch let error as NSError { 

        DispatchQueue.main.async(execute: { 

         session.invalidateAndCancel() 

        }) 
       } 

      } 

     session.finishTasksAndInvalidate() 
     }.resume()