无法识别NSURLSession参数

时间:2016-04-08 03:24:38

标签: swift nsurlsession

我正在尝试使用NSURLSession制作HTTPRequest。当我设置完整网址时,请求会返回正确的数据,但在使用参数时NSJSONSerialization.dataWithJSONObject - > HTTPBody我收到此错误

error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

这里有什么我做错了吗?

 let json = ["api_key": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"]
    do {

        let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

        let url = NSURL(string: "https://api.themoviedb.org/3/discover/movie")!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPBody = jsonData
        request.HTTPMethod = "GET"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")


        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }
            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Result -> \(result)")

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()


    } catch {
        print(error)
    }
}

这不重复!在提出这个问题之前,我查看了建议的答案(没有一个有效)

1 个答案:

答案 0 :(得分:0)

在您的情况下,可以通过将request.HTTPMethod = "GET"更改为request.HTTPMethod = "POST"

来解决问题

你不应该在get请求中发送HTTP Body,要发送带有正文的数据,你应该将HTTPMethod更改为post

注意:请检查此api方法是否支持POST请求,如果它不支持发布,则您无法使用http body / post,仅按照doc i找到'得到'请求discover/movie可以是这样的:

let url = NSURL(string: "http://api.themoviedb.org/3/discover/movie?api_key=YOUR_API_KEY")!
let request = NSMutableURLRequest(URL: url)
request.addValue("application/json", forHTTPHeaderField: "Accept")

let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) { data, response, error in
    if let response = response, data = data {
        print(response)
        print(String(data: data, encoding: NSUTF8StringEncoding))
    } else {
        print(error)
    }
}

task.resume()

参考:您可以查看此网址中的更多信息:http://docs.themoviedb.apiary.io/#reference/discover/discovermovie/get