我将一些数据作为json发布到服务器并从中获取json响应..像这样:
let decoded4 = userDefaults.object(forKey: "nationalities") as! Data
let decodedNationalities = NSKeyedUnarchiver.unarchiveObject(with: decoded4) as! [Nationality]
for nationality in decodedNationalities {
if nationality.name == self.nationality {
idnationality = nationality.id
}
}
if conttype == "Single visit"{
conttype = "single_visit"
}else {
conttype = "multi_visit"
}
print(days)
if days.hasPrefix(","){
days.remove(at: days.startIndex)
}
if days.hasSuffix(","){
days.remove(at: days.endIndex)
}
let todosEndpoint: String = "my link"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "POST"
todosUrlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
let newTodo: [String: Any] = ["email": UserDefaults.standard.string(forKey: "CustomerEmail")!, "password": UserDefaults.standard.string(forKey: "CustomerPassword")!, "id_address": addid, "quantity_staff": maidn, "id_service": idservice, "id_region": idregion, "id_city": idcity, "id_nationality": idnationality, "start_date": "2018-05-09", "contract_type": "single_visit", "shift_type": "day", "weekdays": days, "starttime": starttime, "endtime": endtime]
print(newTodo)
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
} catch {
print("Error: cannot create JSON from todo")
return
}
let session = URLSession.shared
let task = session.dataTask(with: todosUrlRequest) {
(data, response, error) in
guard error == nil else {
print("error calling POST on /public/api/register_customer")
print(error!)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let receivedTodo = try JSONSerialization.jsonObject(with: responseData,options: []) as? [String: Any] else {
print("Could not get JSON from responseData as dictionary")
return
}
print("The todo is: " + receivedTodo.description)
guard let status = receivedTodo["success"] as? Int else {
print("Could not get status from JSON")
return
}
if status == 0{
DispatchQueue.main.async {
self.performSegue(withIdentifier: "segueerr", sender: self)
}
print("The status is: 0")
guard let messages = receivedTodo["message"] as? String else {
print("Could not get messages from JSON")
return
}
print(messages)
}
else {
DispatchQueue.main.async {
self.performSegue(withIdentifier: "successsegue", sender: self)
}
print("Success!")
}
} catch {
print(error)
return
}
}
task.resume()
}
当我运行它时...它发布了正确的值:
[“email”:“lamatat@gmail.com”,“id_service”:3,“id_region”:1, “id_city”:3,“id_address”:22,“weekdays”:“tue”,“contract_type”: “single_visit”,“id_nationality”:4,“密码”: “4169faf51ce3c5fb8850451b441a363906f16d69”,“endtime”:12, “starttime”:8,“shift_type”:“day”,“quantity_staff”:1, “start_date”:“2018-05-09”]
我收到错误的答案是:
错误域= NSCocoaErrorDomain代码= 3840“没有值。” UserInfo = {NSDebugDescription =无值。}
当确定100%的值并且在邮递员中尝试了同样的一个并且得到了这个结果:
{
"success": true,
"message": "Adding new Order was successful.",
"id_order": 210,
"shift": {
"id": 31,
"id_region": 1,
"id_city": 3,
"id_nationality": 4,
"id_service": 3,
"shift_date": "2018-05-09 00:00:00",
"shift_type": "day",
"weekday": "tue",
"quantity_staff": 64,
"lead_hours": 10,
"created_at": "2018-05-07 12:54:48",
"updated_at": "2018-05-09 10:47:37",
"deleted_at": null,
"price_per_visit": 50
}
}
为什么我会从应用程序中收到此错误?!
有人请帮忙!我不知道什么是错的!答案 0 :(得分:0)
试试这个而不是你的。将其更改为
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
以强>
let jsonTodo = JSONStringify(value: newTodo as AnyObject)
在控制器中添加此方法
func JSONStringify(value: AnyObject,prettyPrinted:Bool = false) -> String{
let options = prettyPrinted ? JSONSerialization.WritingOptions.prettyPrinted : JSONSerialization.WritingOptions(rawValue: 0)
if JSONSerialization.isValidJSONObject(value) {
do{
let data = try JSONSerialization.data(withJSONObject: value, options: options)
if let string = NSString(data: data, encoding: String.Encoding.utf8.rawValue) {
return string as String
}
}catch {
print("error")
//Access error here
}
}
return ""
}
*但如果您仍面临同样的问题。改变你的httoBody也像这样
request.httpBody = jsonTodo.data(using: String.Encoding.utf8)