在swift

时间:2016-12-15 07:30:11

标签: swift2 nsurlsession

在使用swift 2.2时,使用NSURLSession时我没有得到响应。我做错了什么?

我必须在POST请求中传递参数和标题。

func API() {

    let userName:String! = "uname"
    let password:String! = "password"

    let request = NSMutableURLRequest(URL: NSURL(string: URL)!)
    request.HTTPMethod = "POST"

    let data = try! NSJSONSerialization.dataWithJSONObject(parameter, options:[])
    let json = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
    request.HTTPBody = json.dataUsingEncoding(NSUTF8StringEncoding)
    request.allHTTPHeaderFields = ["key":"value"]

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()

}

结果是:

  

responseString =可选("")

1 个答案:

答案 0 :(得分:0)

您是否在Postman等任何REST客户端上调用此服务?如果是,请获得回复,请尝试替换此行

request.allHTTPHeaderFields = ["key":"value"]

用这个

request.setValue("value",forHTTPHeaderField:"Key")

并设置所有值