简体   繁体   中英

Syntax of JSON - Body Post request - SWIFT4

I am trying to fetch JSON using an HTTP Post request from the server but I think the body of my request is wrong. I tried everything and can't find a solution. The app is crashing.

I tried some different syntax on the body of the request (newTodo variable) like:

'{"api_key":"mykey123","api_secret":"asdfg","uniqueid":"csd23cdse34ww","password":"secret123","pin":"12345"}'

and

["api_key": "mykey123", "api_secret": "asdfg","uniqueid": "csd23cdse34ww","password": "secret123","pin": "12345"]

Using the above I have the error:

["api_key": "mykey123", "password": "flibble1", "uniqueid": "csd23cdse34ww", "api_secret": "secret123", "pin": "12345"] 2019-01-25 10:00:54.298086+0000 APPTEST[8863:646933] [logging] table "users" already exists table "users" already exists (code: 1) .
error parsing response from POST on /todos

Works fine on Postman with the body

'{ "api_key": "mykey123", "api_secret": "asdfg", "uniqueid": "csd23cdse34ww", "password": "secret123", "pin": "12345", }'

but Xcode asks me to use the syntax below.

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()
}

App is crashing - Thread 1: signal SIGABRT

2019-01-25 09:37:05.762339+0000 APPTEST[8601:615340] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write' *** First throw call stack: ( 0 CoreFoundation 0x00000001087f11bb exceptionPreprocess + 331 1 libobjc.A.dylib 0x000000010635f735 objc_exception_throw + 48 2 CoreFoundation 0x00000001087f1015 +[NSException raise:format:] + 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 0x00000 0010c2b23da -[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 GraphicsServices 0x000000011047c1dd GSEventRunModal + 62 22 UIKitCore 0x000000010c87581d UIApplicationMain + 140 23 APPTEST 0x0000000105896517 main + 71 24 libdyld.dylib 0x0000000108d93575 start + 1 25 ??? 0x0000000000000001 0x0 + 1 ) libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

  • Expected Status code 200

I am pretty sure you do not send what you expect. As it seems you try to JSON-encode a String that "already is" JSON. You should print out the contents of your jsonTodo (and you will be surprised how much escapes you will see ..). JSONSerialization will probably do the right thing if you pass it a Dictionary , but it is much more Swifty to perform these kind of conversions through JSONDecoder and the Codeable protocol.

You should reduce your question to the actual problem at hand in order for people to help. Try to concentrate on creating the correct JSON in your Data object, once you get that things will fall into place.

In order to get a concrete answer to your current problem you should amend your question with the contents of jsonTodo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM