我是使用
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 }
您无法返回异步任务.你必须使用回调.
原文链接:https://www.f2er.com/swift/319614.html像这样添加一个回调:
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,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) }