2016-02-09 52 views
0

我怎樣才能從NSUrlSession返回一個NSHttpUrlResponse狀態代碼。 我對這種語言很陌生。所以,如果還有其他更好的做法,請告訴我。我的代碼就在這裏。我怎樣才能返回從NSUrlSession的NSHttpUrlResponse狀態代碼

//Method to return a status code 
     func responseCode() -> Int{ 
     var responseCode : Int=0 
     if Reachability.isConnectedToNetwork() == true { 
     // get news feed url 
     let url = NSURL(string: baseUrl) 
     let session = NSURLSession.sharedSession() 
//create request 
     let request = NSMutableURLRequest(URL: url!) 
     request.HTTPMethod = httpMethod 
//check null value 
     if (bodyData != "") { 
      request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding); 
     } 
     if (auth != "") { 
      print("Token Auth : \(auth)") 
      request.addValue("bearer \(self.auth)", forHTTPHeaderField:  "Authorization") 
     } 
     print("request : \(request)") 

//How to return a Integer from this below function 
     let task = session.dataTaskWithRequest(request,  completionHandler: {(data, response, error) -> Void in 
      print("Error\(error)") 
      if let httpResponse = response as? NSHTTPURLResponse { 
       print("HttpReponse\(httpResponse.statusCode)") 
       // Get a status code and assign it in a variable 
       responseCode = httpResponse.statusCode 
      } 
     }) 
     task.resume() 
//Return a response code in ViewController but it just return a initial set value that is 0 
     return responseCode 
     } 
//Return a responseCode in ViewController but it just return a initial set value that is 0 
    return responseCode 
    } 
+0

我有看到這個以前而是因爲我很新的語言無法理解了。你可以請編輯我的代碼。 – user3797004

回答

3

這裏session.dataTaskWithRequest是一個異步任務,即它會在另一個線程(除主線程以外)和它的關閉被稱爲當你從服務器響應將被調用。

所以你在這裏做的是你試圖返回responseCode這是在主線程中調用,即它會返回之前,你有任何迴應。

你應該使用完成處理:

func responseCode(completion: (statusCode:Int) ->()){ 
     if Reachability.isConnectedToNetwork() == true { 

      let url = NSURL(string: baseUrl) 
      let session = NSURLSession.sharedSession() 

      let task = session.dataTaskWithRequest(request,completionHandler: {(data, response, error) -> Void in 
       print("Error\(error)") 

       if let httpResponse = response as? NSHTTPURLResponse { 

        print("HttpReponse\(httpResponse.statusCode)") 
        // Get a status code and assign it in a variable 
        completion(statusCode: httpResponse.statusCode) 

       } 
      }) 
      task.resume() 
     } 
    } 

使用此功能如下:

responseCode { (statusCode) ->() in 
      print("Status Code:\(statusCode)") 
    } 
+0

我稱以這種方式 connection.responseCode此函數({ 的StatusCode - >空隙中 打印(「ResponseCode \(的StatusCode)」) }) 這是一個正確的方式,因爲米沒有得到的值。 – user3797004

+0

你有沒有在你的代碼中設置'bodyData'和'auth',因爲我刪除了一些你的代碼,只是爲了專注於'處理程序' –

+0

雅我已經做的事情。即使我在該函數的頂部有一個打印代碼,即使該打印沒有顯示在日誌中。 – user3797004