我正在尝试使用来自服务器的HTTP Post请求来获取JSON,但我认为请求的正文有误。我尝试了一切,但找不到解决方案。该应用程序崩溃了。
我在请求的正文(newTodo变量)上尝试了一些不同的语法,例如:
'{“ api_key”:“ mykey123”,“ api_secret”:“ asdfg”,“ uniqueid”:“ csd23cdse34ww”,“ password”:“ secret123”,“ pin”:“ 12345”}'
和
[“ api_key”:“ mykey123”,“ api_secret”:“ asdfg”,“ uniqueid”:“ csd23cdse34ww”,“ password”:“ secret123”,“ pin”:“ 12345”]
使用上面我有错误:
[“ api_key”:“ mykey123”,“ password”:“ flibble1”,“ uniqueid”:“ csd23cdse34ww”,“ api_secret”:“ secret123”,“ pin”:“ 12345”]
2019-01-25 10:00:54.298086 + 0000 APPTEST [8863:646933] [记录]表“用户”已存在
表“用户”已经存在(代码:1)。
解析来自/ todos上POST的响应时出错
在邮递员身上可以正常工作
'{
“ api_key”:“ mykey123”,
“ api_secret”:“ asdfg”,
“ uniqueid”:“ csd23cdse34ww”,
“ password”:“ secret123”,
“ pin”:“ 12345”,
}'
但是Xcode要求我使用以下语法。
func loginPressed() {
let todosEndpoint: String = "https://mydevapi.com/authenticateuser"
guard let todosURL = URL(string: todosEndpoint) else {
print("Error: cannot create URL")
return
}
var todosUrlRequest = URLRequest(url: todosURL)
todosUrlRequest.httpMethod = "POST"
let newTodo = "{\"api_key\":\"mykey123\",\"api_secret\":\"asdfg\",\"uniqueid\":\"csd23cdse34ww\",\"password\":\"secret123\",\"pin\":\"12345\"}"
let jsonTodo: Data
do {
jsonTodo = try JSONSerialization.data(withJSONObject: newTodo, options: [])
todosUrlRequest.httpBody = jsonTodo
print(newTodo)
} 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 /todos/1")
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(receivedTodo)
print("The todo is: " + receivedTodo.description)
guard let todoID = receivedTodo["id"] as? Int else {
print("Could not get todoID as int from JSON")
print(receivedTodo)
return
}
print("The ID is: \(todoID)")
print(receivedTodo)
} catch {
print("error parsing response from POST on /todos")
return
}
}
task.resume()
}
应用程序崩溃-线程1:信号SIGABRT
2019-01-25 09:37:05.762339 + 0000 APPTEST [8601:615340] *由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'* + [NSJSONSerialization dataWithJSONObject:options:error:]:无效的顶级类型JSON写入”
***首先抛出调用堆栈:
(
0 CoreFoundation 0x00000001087f11bb异常预处理+ 331
1 libobjc.A.dylib 0x000000010635f735 objc_exception_throw + 48
2 CoreFoundation 0x00000001087f1015 + [NSException提高:格式:] + 197
3 Foundation 0x0000000105eb2dd5 + [NSJSONSerialization dataWithJSONObject:options:error:] + 253
4 APPTEST 0x000000010588ab5e $ S9Bibimoney15LoginControllerC12loginPressedyyF + 2718
5 APPTEST 0x000000010588f79c $ STA.7 + 28
6 APPTEST 0x00000001058924d4 $ S9Bibimoney9LoginViewC06handleB0yyF + 132
7 APPTEST 0x0000000105892534 $ S9Bibimoney9LoginViewC06handleB0yyFTo + 36
8 UIKitCore 0x000000010c876ecb-[UIApplication sendAction:to:from:forEvent:] + 83
9 UIKitCore 0x000000010c2b20bd-[UIControl sendAction:to:forEvent:] + 67
10 UIKitCore 0x000000010c2b23da-[UIControl _sendActionsForEvents:withEvent:] + 450
11 UIKitCore 0x000000010c2b131e-[UIControl touchesEnded:withEvent:] + 583
12 UIKitCore 0x000000010c8b20a4-[UIWindow _sendTouchesForEvent:] + 2729
13 UIKitCore 0x000000010c8b37a0-[UIWindow sendEvent:] + 4080
14 UIKitCore 0x000000010c891394-[UIApplication sendEvent:] + 352
15 UIKitCore 0x000000010c9665a9 __dispatchPreprocessedEventFromEventQueue + 3054
16 UIKitCore 0x000000010c9691cb __handleEventQueueInternal + 5948
17 CoreFoundation 0x0000000108756721 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION + 17
18 CoreFoundation 0x0000000108755f93 __CFRunLoopDoSources0 + 243
19 CoreFoundation 0x000000010875063f __CFRunLoopRun + 1263
20 CoreFoundation 0x000000010874fe11 CFRunLoopRunSpecific + 625
21图形服务0x000000011047c1dd GSEventRunModal + 62
22 UIKitCore 0x000000010c87581d UIApplicationMain + 140
23 APPTEST 0x0000000105896517主+ 71
24 libdyld.dylib 0x0000000108d93575开始+ 1
25 ??? 0x0000000000000001 0x0 + 1
)
libc ++ abi.dylib:以NSException类型的未捕获异常终止
(lldb)
预期状态码200
最佳答案
我很确定您不会寄出您所期望的。看来您尝试对“已经是” JSON的字符串进行JSON编码。您应该打印出jsonTodo
的内容(您会惊讶地发现会有多少转义。)。如果将JSONSerialization
传递给Dictionary
,它可能会做正确的事,但是通过JSONDecoder
和Codeable
协议执行此类转换将更加快捷。
您应该将问题简化为眼前的实际问题,以便人们提供帮助。一旦您意识到事情将就位,请尝试集中精力在Data
对象中创建正确的JSON。
为了得到您当前问题的具体答案,您应该使用jsonTodo
的内容修改您的问题。