我是iOS編程新手,我正在嘗試使用Swift新語言。 我有一個問題/我不知道如何解析與iOS的Swift的JSON使用。我已經使用JSON在Android的,所以我知道,JSON和鏈接是正確的,但是當我嘗試下面的代碼(在教程中看到的)的應用程序似乎崩潰,並強調這一行:JSON解析Swift錯誤
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
的控制檯給我回這個錯誤:
The operation couldn’t be completed. (NSURLErrorDomain error -1005.) fatal error: unexpectedly found nil while unwrapping an Optional value
這裏是按鈕的操作的全部代碼:
let urlAsString = "http://xxxxxxxxxx.altervista.org/App/_DD_/downloadutenti.php?email="+campoEmail.text+"&password="+campoPassword.text
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
println(url)
println(urlSession)
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
if(data != nil){
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
var jsonEmail = ""
if var jsonEmail: String! = jsonResult["email"] as? NSString{
}
else{
println("PROBLEM 1")
}
var jsonPassword = ""
if var jsonPassword: String! = jsonResult["pass"] as? NSString{
}
else{
println("PROBLEM 2")
}
dispatch_async(dispatch_get_main_queue(), {
self.scritta2.text = "Email: " + jsonEmail + " - Password: " + jsonPassword
})
}
})
jsonQuery.resume()
NB 我使用xcode6模擬器,我知道肯定的「變量」campoEmail.text和campoPassword.text採取了一個好方法。
JSON它應該給予回覆:
[{"id":"1","email":"[email protected]","password":"pass","permessi":"1","stato":"Italia","citta":"Palermo","via":"Via Lincoln, 29","cap":"90100","telefono":"091xxxxxx"}]
編輯@ neo的幫助: 我編輯喜歡這個按鈕的所有動作,但代碼進入到數據的空檢查..
let curURL: NSURL = NSURL(string: "http://fantacharleston.altervista.org/App/_DD_/[email protected]&password=pass")!
let curRequest: NSURLRequest = NSURLRequest(URL: curURL, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 60)
NSURLConnection.sendAsynchronousRequest(curRequest, queue: NSOperationQueue.mainQueue()) { (response: NSURLResponse!, data: NSData?, error: NSError!) -> Void in
if (data != nil) {
if let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSArray? {
let jsonObject: NSDictionary? = jsonArray.objectAtIndex(0) as? NSDictionary
if (jsonObject != nil) {
NSLog("object: %@", jsonObject!)
let email: NSString? = jsonObject?.objectForKey("email") as? NSString
let password: NSString? = jsonObject?.objectForKey("password") as? NSString
if (email != nil && password != nil) {
dispatch_async(dispatch_get_main_queue(), {() -> Void in
self.scritta2.text = "Email: " + email! + " - Password: " + password!
})
}
}
}
}
else{
println("null")
}
}
你能否爲我提供JSON的一部分解析? – 2014-12-05 21:12:06
當然,您應該收到您收到的全部錯誤消息。 – 2014-12-05 21:41:21
我添加了它應該回饋的內容。 @Neo – 2014-12-05 21:44:53