我是使用Swift语言进行iOS开发的初学者。我有一个包含以下数据的JSON文件。
{ "success": true, "data": [ { "type": 0, "name": "Money Extension", "bal": "72 $", "Name": "LK_Mor", "code": "LK_Mor", "class": "0", "withdraw": "300 $", "initval": "1000 $" }, { }, { }, ] }
我想解析此文件,并且必须返回包含JSON文件中数据的字典。这是我写的方法。
enum JSONError: String, ErrorType { case NoData = "ERROR: no data" case ConversionFailed = "ERROR: conversion from JSON failed" } func jsonParserForDataUsage(urlForData:String)->NSDictionary{ var dicOfParsedData :NSDictionary! print("json parser activated") let urlPath = urlForData let endpoint = NSURL(string: urlPath) let request = NSMutableURLRequest(URL:endpoint!) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in do { guard let dat = data else { throw JSONError.NoData } guard let dictionary: NSDictionary = try NSJSONSerialization.JSONObjectWithData(dat, options:.AllowFragments) as? NSDictionary else { throw JSONError.ConversionFailed } print(dictionary) dicOfParsedData = dictionary } catch let error as JSONError { print(error.rawValue) } catch { print(error) } }.resume() return dicOfParsedData }
当我修改此方法以返回字典时,它总是返回nil。如何修改此方法。
您不能return执行异步任务。您必须改用回调。
return
添加这样的回调:
completion: (dictionary: NSDictionary) -> Void
解析器方法签名:
func jsonParserForDataUsage(urlForData: String, completion: (dictionary: NSDictionary) -> Void)
并在您要“返回”的数据可用的地方调用补全:
func jsonParserForDataUsage(urlForData: String, completion: (dictionary: NSDictionary) -> Void) { print("json parser activated") let urlPath = urlForData guard let endpoint = NSURL(string: urlPath) else { return } let request = NSMutableURLRequest(URL:endpoint) NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in do { guard let dat = data else { throw JSONError.NoData } guard let dictionary = try NSJSONSerialization.JSONObjectWithData(dat, options:.AllowFragments) as? NSDictionary else { throw JSONError.ConversionFailed } completion(dictionary: dictionary) } catch let error as JSONError { print(error.rawValue) } catch let error as NSError { print(error.debugDescription) } }.resume() }
现在,您可以将此方法与结尾的闭包一起使用,以获取“返回的”值:
jsonParserForDataUsage("http...") { (dictionary) in print(dictionary) }