简体   繁体   中英

Parsing JSON from PHP in Swift 4

I'm getting an error when loading JSON from a PHP output page using Swift 4.

Note: The PHP script has been checked and is working fine

let myUrl = URL(string: "http://localhost/swift/signin_up/login.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
DispatchQueue.main.async {
    let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
        if error != nil {
            print("error=\(error!)")
            return
        }

        // You can print out response object
        print("response = \(response!)")
        print("==================================")
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            if let parseJSON = json {
                print(parseJSON)
            }
        } catch {
            print(" error:\(error)")
        }
    }
    task.resume()

I get this error message from Xcode:

error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

When I changed options to:

options: [.mutableContainers, .allowFragments]

I get this error message:

error: Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}

This is the PHP output I tested:

{"id":"1","email":"aa","password":"aa"}

Be careful when you set character_set in database server choose (utf8_unicode_ci) to get correct json format when using

json_encode(//json variable);

in php

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