2017-04-14 121 views
3

我卡住與HTTP request.it沒有顯示出任何error.compiler讀取的前兩行,並跳過碼的「task.resume()」。我與相同取數據其他視圖控制器代碼,但它的問題。外幣這裏HTTP請求8.3

func getCustomers() 
{ 
    let url = NSURL(string: "myURL.com") 
    let task = URLSession.shared.dataTask(with: url! as URL) { 
     (data, response, error) in 

     guard let _:Data = data, let _:URLResponse = response , error == nil else { 
      print("error: \(String(describing: error))") 

      return 
     } 
     do 
     { 
      self.getcustomersArray = [GetCustomers]() 
      //JSON Parsing 
      if let data = data, 

       let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] 
      { 
       let results = json["Result"] as? [[String : Any]] 

       let getCustomersObject:GetCustomers = GetCustomers() 
       for result in results! 
       { 
        getCustomersObject.ActivityPrefix = (result["ActivityPrefix"] as? String)! 
        getCustomersObject.CustomerID = (result["CustomerID"] as? String)! 
        getCustomersObject.CustomerName = (result["CustomerName"] as? String)! 
        getCustomersObject.TFMCustomerID = (result["TFMCustomerID"] as? String)! 
        getCustomersObject.ShortName = (result["ShortName"] as? String)! 
        getCustomersObject.UserRights = (result["UserRights"] as? Int)! 

        self.totalCustomers += self.totalCustomers 
       } 
       self.customerName = getCustomersObject.CustomerName 

      } 
     }//end Do 
     catch 
     { 

     } 
    } 

    task.resume() 
} 
+0

其明顯的,因爲'dataTask'完成塊會再打,當你得到迴應 –

+2

問題是什麼? – vadian

+0

它正在創建什麼問題? –

回答

1

使用塊GET/POST/PUT/DELETE:

let request = NSMutableURLRequest(url: URL(string: "Your API URL here" ,param: param))!, 
     cachePolicy: .useProtocolCachePolicy, 
     timeoutInterval:"Your request timeout time in Seconds") 
    request.httpMethod = "GET" 
    request.allHTTPHeaderFields = headers as? [String : String] 

    let session = URLSession.shared 

    let dataTask = session.dataTask(with: request as URLRequest) {data,response,error in 
     let httpResponse = response as? HTTPURLResponse 

     if (error != nil) { 
     print(error) 
     } else { 
     print(httpResponse) 
     } 

     DispatchQueue.main.async { 
      //Update your UI here 
     } 

    } 
    dataTask.resume() 

我想你不提線 request.httpMethod = 「GET」

+2

新對於GET請求不需要一個明確的'URLRequest'和斯威夫特3使用本地'URLRequest'而不是'NSMutableURLRequest'。 – vadian

+0

謝謝你分享你的知識。我的意思是他錯過了httpMethod請求。 –

+1

基本上在問題的代碼** **是工作,得到的是默認的。 – vadian