0

I am new to Swift. Trying to make a post request to laravel on localhost. To verify my Request recieved from swift within laravel. I am returning Request as JSON response. which produces this error.

Code 3840 "JSON text did not start with array or object and option to allow fragments not set."

Which means a malformed JSON response.

Laravel UserController

public function verify_login(Request $request)
{
  return response()->json($request)
}

ViewController.swift

 @IBAction func verify_login(_ sender: UIButton) {
    let username: String = self.username.text!
    let passkey: String = self.passkey.text!
    //print(username)
    let urlString = "http://localhost:8888/user/verify"

    guard let requestUrl = URL(string:urlString) else { return }

    let parameters = "username=\(username)&passkey=\(passkey)"
    var request = URLRequest(url:requestUrl)
    request.httpMethod = "POST"
    request.setValue("application/x-www-form-unlencoded;charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.httpBody = parameters.data(using: String.Encoding.utf8)

    let task = URLSession.shared.dataTask(with: request) {
        (data, response, error) in
        if error == nil,let usableData = data {
            var json: [String: Any]?
            do {
                json = try JSONSerialization.jsonObject(with: usableData) as? [String:Any]
                print(json?["username"]! as Any)

            }catch{
                print(error)
            }
        }
    }

    task.resume()
    }

NOTE:

  1. Using Postman I recieve the expected response (Request object as json).
  2. Swift end code works fine with JSON Placeholder API
Nauman Zafar
  • 1,083
  • 15
  • 40
  • If you are just testing, try simply `return $request;`, Laravel will generate JSON automatically. – Don't Panic Sep 16 '17 at 09:43
  • I already have tried that. In both cases the `content-type` is `application/json` but it doesn't work. – Nauman Zafar Sep 16 '17 at 09:45
  • In that case, this seems to be a duplicate of https://stackoverflow.com/questions/14171111/cocoa-error-3840-using-json-ios. You need to pass `NSJSONReadingAllowFragments`. The returned JSON simply does not have a top level container. – Don't Panic Sep 16 '17 at 09:49
  • I have checked it but now the error says "Invalid value around character 0". Debug results how the data received has 0 length. I mean data received is nil. Same api call gives data in postman. – Nauman Zafar Sep 16 '17 at 10:28
  • 1
    If the data is 0 length via Swift but not via Postman, you have some other problem. `return $request;` does not change between clients. – Don't Panic Sep 16 '17 at 10:32
  • Agreed. Now on my way to investigate that. – Nauman Zafar Sep 16 '17 at 10:34

0 Answers0