从下面的代码中,它没有显示任何错误,但它得到运行时appDelegate错误,其原因是由于未捕获的异常而终止应用程序' NSInvalidArgumentException'。请告诉我要做什么来摆脱这个......
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)
}
}
答案 0 :(得分:1)
使用以下扩展名将数据转换为JSON对象:
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."
}
}
回应
let info = response.data?.JSONObject()