已有代码:
var decodedJsonDict:JSON? let fullNsurl: NSURL = NSURL(string: url)! print("fullNsurl=\(fullNsurl)") let urlReq: NSURLRequest = NSURLRequest(URL: fullNsurl) print("urlReq=\(urlReq)") do { let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil let respJsonData: NSData = try NSURLConnection.sendSynchronousRequest(urlReq, returningResponse: response) //print("response=\(response)") //response=0x0000000000000000 //print("respJsonData=\(respJsonData)") decodedJsonDict = JSON(data: respJsonData) print("decodedJsonDict=\(decodedJsonDict)") }catch let httpGetErr { print("httpGetErr=\(httpGetErr)") decodedJsonDict = nil }
现在需要,添加header
Accept:application/json
Content-Type:application/json
搜:
swift NSURLConnection add header
参考:
var decodedJsonDict:JSON? let fullNsurl: NSURL = NSURL(string: url)! print("fullNsurl=\(fullNsurl)") // let urlReq: NSURLRequest = NSURLRequest(URL: fullNsurl) let mutableUrlReq:NSMutableURLRequest = NSMutableURLRequest(URL: fullNsurl) //add header // mutableUrlReq.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Content-Type") mutableUrlReq.addValue("application/json", forHTTPHeaderField: "Accept") do { let response: AutoreleasingUnsafeMutablePointer<NSURLResponse? >= nil let respJsonData: NSData = try NSURLConnection.sendSynchronousRequest(mutableUrlReq, returningResponse: response) decodedJsonDict = JSON(data: respJsonData) print("decodedJsonDict=\(decodedJsonDict)") }catch let httpGetErr { print("httpGetErr=\(httpGetErr)") decodedJsonDict = nil }
即可。
转载请注明:在路上 » [已解决]swift 给NSURLConnection NSURLRequest添加header