使用 Alamofire 在 Swift 中下载和解析 json
Downloading and parsing json in Swift with Alamofire
抱歉,我对此很陌生,它们可能是我头脑中显而易见的东西,但我收到以下代码的错误消息:
"fatal error: unexpectedly found nil while unwrapping an Optional value."
var jsonReceived = Alamofire.request(.GET, getJsonURL).responseJSON {
(request, response, jsonData, error) in
if jsonData == nil {
println(error)
} else {
println(jsonData)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
为了简单起见,我将 Alamofire.request
代码放入了 viewDidLoad()
。你可以把它放在任何你想放的地方。
override func viewDidLoad() {
Alamofire.request(.GET, getJsonURL).responseJSON {
(request, response, jsonData, error) in
if error != nil {
println(error)
} else if let json = jsonData as? [String:AnyObject] {
println(json)
// call a function with the new data.
self.processNewData(json)
// or you could just use the json object here
if let str = json["foo"] as? String {
self.myButton.setTitle(str, forState: .Normal)
}
} else {
println("Failed to cast JSON to [String:AnyObject]")
}
}
}
func processNewData(json: [String:AnyObject]){
// do whatever you want here with the parsed JSON
if let str = json["bar"] as? String {
myLabel.text = str
}
}
抱歉,我对此很陌生,它们可能是我头脑中显而易见的东西,但我收到以下代码的错误消息:
"fatal error: unexpectedly found nil while unwrapping an Optional value."
var jsonReceived = Alamofire.request(.GET, getJsonURL).responseJSON {
(request, response, jsonData, error) in
if jsonData == nil {
println(error)
} else {
println(jsonData)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
为了简单起见,我将 Alamofire.request
代码放入了 viewDidLoad()
。你可以把它放在任何你想放的地方。
override func viewDidLoad() {
Alamofire.request(.GET, getJsonURL).responseJSON {
(request, response, jsonData, error) in
if error != nil {
println(error)
} else if let json = jsonData as? [String:AnyObject] {
println(json)
// call a function with the new data.
self.processNewData(json)
// or you could just use the json object here
if let str = json["foo"] as? String {
self.myButton.setTitle(str, forState: .Normal)
}
} else {
println("Failed to cast JSON to [String:AnyObject]")
}
}
}
func processNewData(json: [String:AnyObject]){
// do whatever you want here with the parsed JSON
if let str = json["bar"] as? String {
myLabel.text = str
}
}