Swift JSON parsing with Dictionary with Array of Dictionaries

后端 未结 1 1254
南旧
南旧 2020-12-21 06:16

I am a beginner in iOS development with Swift language. I have a JSON file contains the data as below.

{
    \"success\": true,
    \"data\": [
                      


        
相关标签:
1条回答
  • 2020-12-21 06:45

    You can not return for an asynchronous task. You have to use a callback instead.

    Add a callback like this one:

    completion: (dictionary: NSDictionary) -> Void
    

    to your parser method signature:

    func jsonParserForDataUsage(urlForData: String, completion: (dictionary: NSDictionary) -> Void)
    

    and call the completion where the data you want to "return" is available:

    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()
    
    }
    

    Now you can use this method with a trailing closure to get the "returned" value:

    jsonParserForDataUsage("http...") { (dictionary) in
        print(dictionary)
    }
    
    0 讨论(0)
提交回复
热议问题