代码
let session = URLSession.shared
// prepare json data
let json: [String: Any] = ["email": "[email protected]"]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
let proceedURL = NSURL(string:"https://mysitename.herokuapp.com/api/users/isUser")
//let proceedURL = NSURL(string:"https://google.com")
let request = NSMutableURLRequest(url: proceedURL! as URL)
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/www.inception.v1", forHTTPHeaderField: "Accept")
request.addValue("Authorization", forHTTPHeaderField: "Basic aW5jZXB0aW9uQGZ1cmRvOmljM=")
request.httpMethod = "OST"
//request.httpBody = jsonData
// insert json data to the request
request.httpBody = jsonData
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString!)")
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print("error : " + error.localizedDescription)
}
})
task.resume()
错误:
无法读取数据,因为它的格式不正确。
我是 iphone 应用程序开发的初学者,请帮助我并为建立网络连接提供更好的建议(比如在 android 中我正在使用 Volley 库)
实际 react 是:
{
"status": 1,
"http_status_code": 200,
"data": {
"email": "[email protected]",
"phone": "8090909000"
}
}
我在 Android 上使用相同并在 postman 中进行测试。
// Print out response string
let responseString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
上面的代码响应什么都没有
Best Answer-推荐答案 strong>
使用 Alamofire。
let json: [String: Any] = ["email": "[email protected]"]
Alamofire.request(.POST, "https://mysitename.herokuapp.com/api/users/isUser" , parameters: json, encoding: .JSON).responseJSON {
Response in
switch Response.result {
case .Success(let _data):
let JsonData = JSON(_data)
print("JsonData : \(JsonData)")
//handle json
case .Failure(let _error):
print(_error)
let AlertBox = UIAlertController(title: "Connection Failed", message: "No Connection", preferredStyle: .Alert)
let ActionBox = UIAlertAction(title: "Ok" , style: .Default, handler: { _ in})
AlertBox.addAction(ActionBox)
self.presentViewController(AlertBox, animated: true, completion: nil)
}
关于ios - 无法读取数据,因为它的格式不正确 - HTTP 网络,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/42997965/
|