0
我想從我的Rails Web服務器共享數據到一個具有JSON的Swift應用程序。我正在努力做到這一點。Rails的JSON到Swift 2 JSON
從Rails的控制器:
...
output = x.to_json
render :json => output
...
在斯威夫特iOS應用:
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
reachForWebsite()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func reachForWebsite(){
let url = NSURL(string: "myURL")
let request = NSURLRequest(URL: url!)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data!, encoding: NSUTF8StringEncoding))
var error: NSError? = nil
if let jsonObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error = &error){
if let dict = jsonObject as? NSDictionary {
println(dict)
} else {
println("not a dictionary")
}
} else {
println("Could not parse JSON: \(error!)")
}
println(data.dynamicType)
}
}
task!.resume()
}
}
我可以確認我成功接收數據,因爲我可以將其轉換爲字符串,並將其打印到應用程序的控制檯。我無法從它創建一個NSDictionary對象。這些錯誤隨每個修補程序而改變,但涉及到可選項並嘗試捕獲。
JSON
{"inside":[{"name":"BOB"}, ...],"outside":[{"name":"TIM","type":"HUMAN","id":1}, ...],"info":{"time":"2015-07-02"}}
你可以發佈一個你正在解析的JSON的例子嗎? –
這聽起來像你的JSON格式有問題,或者它可能是一個數組而不是字典?此外,這可能或不是你正在尋找的答案的一部分,但這是一個愉快的機會,用開關盒打開optionals:https://gist.github.com/patricklynch/8d5b792c5fa2aad95fe7 –
@PatrickLynch更新的問題與JSON格式 – Marcus