imac apple
imac apple

Reputation: 53

Getting an AppDelegate Error while json parsing using Alamofire

From the below code it doesn't show any error but it gets run time appDelegate error and its reason is Terminating app due to uncaught exception 'NSInvalidArgumentException'. Please, tell what I want to do to get rid of this...

var urlstring: String!

     urlstring = "\(signInAPIUrl)rooms/room_type"
    urlstring = urlstring.replacingOccurrences(of: "Optional(", with: "")
    urlstring = urlstring.replacingOccurrences(of: ")", with: "")
    urlstring = urlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)!

    print(urlstring)
    self.callSiginGBAPI(url: "\(urlstring!)")
       }
func callSiginGBAPI(url : String){

    print("url: \(url)")

    Alamofire.request(url).responseJSON { (response) in

        self.parseDataGB(JSONData: response.data!)

        print("Response:\(response)")

    }

}
func parseDataGB(JSONData : Data){

    do{

        let readableJSon = try JSONSerialization.jsonObject(with: JSONData, options: .mutableContainers) as! jsonSTD

        print(" !!! \(readableJSon[0])")

        let value = readableJSon[0] as AnyObject

        if let final = value.object(forKey: "id")
        {
            print(final)

            let first_name:String = value.object(forKey: "id") as! String
            let last_name:String = value.object(forKey: "type") as! String
            let list_type:String = value.object(forKey: "list_type") as! String
            print(first_name)
            print(last_name)
            print(list_type)

        } else{
        }
    }
    catch{

        print(error)

    }

}

Upvotes: 1

Views: 95

Answers (1)

Phani Sai
Phani Sai

Reputation: 1233

Use the following extension to convert data to JSON object:

extension Data {
      func JSONObject() -> AnyObject? {
        do {
            let content = try JSONSerialization.jsonObject(with: self as Data, options: JSONSerialization.ReadingOptions.allowFragments)
            return content as AnyObject?
        } catch _ as NSError {
            return nil
        }
    }

    var string: String {
        return String(data: self as Data, encoding: String.Encoding.utf8) ?? "Error: Not able to get string from the data."
    }

}

in response

let info = response.data?.JSONObject() 

Upvotes: 1

Related Questions