【问题标题】:iOS URLRequest POST Failing Swift [closed]iOS URLRequest POST Swift 失败 [关闭]
【发布时间】:2017-10-29 07:00:14
【问题描述】:

我目前正在尝试使用 JSON 正文在 iOS 平台上发出 POST 请求。我的请求在 cURL 中有效,但我无法让它在 iOS 中工作;请求超时。这是我的快速代码:

    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)
    }
}

当我调用此函数时,请求不起作用...我确定我使用的是正确的 url,因为它适用于 GET 端点。我错过了任何标题吗?如果您发现请求有问题,请告诉我。

【问题讨论】:

    标签: ios json swift http post


    【解决方案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()
    

    谢谢。

    【讨论】:

    • 感谢您的回答...很抱歉,即使使用您的方法,请求仍然超时。还有其他想法吗?
    【解决方案2】:

    我将自己发布一个答案,因为它可能会在未来帮助某人。我正在使用设备发出请求,并且正在向 localhost 发出请求。我太笨了,手机上的wifi都关了.....

    【讨论】:

      猜你喜欢
      • 2017-11-11
      • 2019-09-24
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2021-11-15
      • 2016-05-14
      相关资源
      最近更新 更多