0

I was creating the iOS app with MYSQL. In app I used below code.

import UIKit

class ViewController: UIViewController {

//URL to our web service
let URL_SAVE_TEAM = URL(string:"http://my_url/ios_api/api/createteam.php")

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

//TextFields declarations
@IBOutlet weak var textFieldName: UITextField!
@IBOutlet weak var textFieldMember: UITextField!

@IBAction func buttonSave(_ sender: UIButton) {

    //creating NSMutableURLRequest
    let request = NSMutableURLRequest(url: URL_SAVE_TEAM!)

    //setting the method to post
    request.httpMethod = "GET"

    //getting values from text fields
    let teamName=textFieldName.text
    let memberCount = textFieldMember.text

    //creating the post parameter by concatenating the keys and values from text field
    let postParameters = "name="+teamName!+"&member="+memberCount!;

    //adding the parameters to request body
    request.httpBody = postParameters.data(using: String.Encoding.utf8)


    //creating a task to send the post request
    let task = URLSession.shared.dataTask(with: request as URLRequest){
        data, response, error in

        if error != nil{
            print("error is \(error)")
            return;
        }

        //parsing the response
        do {
            //converting resonse to NSDictionary
            let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

            //parsing the json
            if let parseJSON = myJSON {

                //creating a string
                var msg : String!

                //getting the json response
                msg = parseJSON["message"] as! String?

                //printing the response
                print(msg)

            }
        } catch {
            print(error)
        }

    }
    //executing the task
    task.resume()
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

On that line of code, it show the below error. I have searched in google and can't find the solution. Please help me to fix this.

let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

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.}

Kawazoe Kazuke
  • 175
  • 6
  • 20
  • The error says, it's not valid JSON. By the way, why `.mutableContainers`? You are assigning the result to an immutable dictionary and don't use `NS...` collection types and `NSMutableURLRequest` in Swift at all. I guess the issue is you are using a GET request but you pass (POST) parameters in the http body which doesn't work. – vadian Apr 05 '18 at 07:25
  • 1
    Use `JSONSerialization.jsonObject(with: data!, options: nil)` or `JSONSerialization.jsonObject(with: data!)`. it will work – Ankit Jayaswal Apr 05 '18 at 07:25
  • #Ankit Jayaswa, I tried with your code bro, but it doesn't work. :( – Kawazoe Kazuke Apr 05 '18 at 07:35
  • Very probably your server is returning an error result which is not a JSON. What do you get with putting this before `//parsing the response`? `print(String(data: data!, encoding: .utf8) ?? "???")` – OOPer Apr 05 '18 at 07:45
  • Do you ming giving use `let reponseString = String.init(data:data, encoding:.utf8)`? Or at least check if it's JSON valid on a JSON validator? – Larme Apr 05 '18 at 08:05
  • Possible duplicate of [error while doing JSON Serialization ErrorDomain Code=3840](https://stackoverflow.com/questions/47950757/error-while-doing-json-serialization-errordomain-code-3840) – AshvinGudaliya Apr 05 '18 at 11:50

0 Answers0