2017-05-29 77 views
-2

我目前正在嘗試使用JSON正文在iOS平臺上發出POST請求。我的請求使用cURL,但我無法在iOS中使用它;請求超時。這裏是我的SWIFT代碼:iOS URLRequest POST失敗Swift

class func createNewChannel(name: String, priv: String, channelKey: String, handle: String, password: String, auth: String) { 
    let baseURL = "http://10.0.0.220:3000/" 

    let dict = ["name": name, "private": priv, "channelKey": channelKey, "handle": handle, "password": password, "auth": auth] as [String : Any] 
    let jsonData = JSON(dict) 
    do { 
     let post = try jsonData.rawData() 
     let postLength = String(post.count) 
     let url = URL(string: "\(baseURL)channel/createChannel")! 
     var request = URLRequest(url: url) 
     request.httpMethod = "POST" 
     request.httpBody = post as Data 
     request.setValue(postLength, forHTTPHeaderField: "Content-Length") 
     request.setValue("application/json", forHTTPHeaderField: "Content-Type") 
     request.setValue("application/json", forHTTPHeaderField: "Accept") 

     let session = URLSession.shared 
     let task = session.dataTask(with: request, completionHandler: { (data, response, error) in 
      if error == nil { 
       do { 
        let json = try JSON(data: data!) 
        print(json) 
       } 
       catch { 
        print(error.localizedDescription) 
       } 
      } 
      else { 
       print(error!) 
      } 
     }) 
     task.resume() 
    } 
    catch { 
     print(error.localizedDescription) 
    } 
} 

當我調用此函數,該請求不工作...我相信我使用的是正確的網址,因爲它有一個GET端點工作。我是否缺少任何標題?如果您發現請求出現問題,請告訴我。

回答

1

請試試這個。

let session = URLSession.shared 
    let request = URLRequest(url:url) 
    request.addValue("application/json", forHTTPHeaderField: "Content-Type") 

    request.httpMethod = "POST" 
     do { 
      let data = try JSONSerialization.data(withJSONObject: yourParam!, options:JSONSerialization.WritingOptions(rawValue: 0)) 
      let mappedString : String = (String(data: data , encoding: String.Encoding.utf8)!) 
      request.httpBody = mappedString.data(using: String.Encoding.utf8, allowLossyConversion: false) 
     } 
     catch let error as NSError 
     { 
      print("JSON ERROR 1  " + error.localizedDescription) 
      closure(Result.failure(error)) 
      return 
     } 
    let task = session.dataTask(with: request, completionHandler: { 
     (data, response, error) in 
     DispatchQueue.main.async { 
      guard data != nil && error == nil else { 
       print(error) 
       return 
      } 
      do { 
       let jsonResult : NSDictionary? = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary 
       print("jsonResult\(jsonResult!)") 
      } catch let error as NSError { 
       print("JSON ERROR 2  " + error.localizedDescription) 
      } 
    } 
}) 
       task.resume() 

謝謝。

+0

感謝您的回答......我很抱歉地說,即使您的方法請求仍然超時。任何其他想法? –

2

我只是想自己發表一個答案,因爲它可能會在未來幫助別人。我正在使用設備發出請求,並且正在向本地主機發出請求。我太笨了,我的手機上沒有wifi了......