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:
- Using
Postman
I recieve the expected response (Request object as json). - Swift end code works fine with JSON Placeholder API