2016-04-04 113 views
2

我是一個用iOS開發Swift語言的初學者。我有一個JSON文件包含如下的數據。Swift 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。我怎樣才能修改這個方法。

+0

什麼是錯誤? –

+0

@BlakeLockley用於定義端點的警戒聲明給我錯誤。我不知道如何解決它 – madhev

+0

也許你的網址路徑格式錯誤?你可以和我們分享嗎? –

回答

1

對於異步任務,您不能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) 
} 
+0

謝謝。它正在工作 – madhev