Reputation: 1319
I'm working on a json retrieving project or whatever, and I'm getting a fatal error while unwrapping a json. I think that the issue is that url is nil and I'm trying to unwrap it, but I'm not sure.
func getXRPData(urlString: String){
let url = NSURL(string: urlString)
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) in
dispatch_async(dispatch_get_main_queue(), {
self.setLabels(data)
})
}
task.resume()
}
func setLabels(xrpDataL: NSData){
var jsonError: NSError?
var percent = "%"
var dollarSIGN = "$"
let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as! NSDictionary
//supply of xrp
if let supply = json["supply"] as? String{
var numberFormatter = NSNumberFormatter()
numberFormatter.numberStyle = NSNumberFormatterStyle.DecimalStyle
if let result = numberFormatter.numberFromString(supply){
var finalResult = numberFormatter.stringFromNumber(result)
totalXRP.text = finalResult
}
}
Upvotes: 0
Views: 67
Reputation: 2782
Instead of force unwrapping, you should unwrap the results of JSONObjectWithData
with an optional binding (if let
) and a conditional downcast (as?
):
if let json = NSJSONSerialization.JSONObjectWithData(xrpDataL, options: nil, error: &jsonError) as? NSDictionary {
// Continue parsing
} else {
// Handle error
}
Upvotes: 1