3

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

{
    "success": true,
    "data": [
             {
                 "type": 0,
                 "name": "Money Extension",
                 "bal": "72 $",
                 "Name": "LK_Mor",
                 "code": "LK_Mor",
                 "class": "0",
                 "withdraw": "300 $",
                 "initval": "1000 $"
             },
             {

             },
             {

             },
             ]
}   

I want to parse this file and have to return the dictionary which contain the data in the JSON file. This is the method I wrote.

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

}

When I modify this method to return a dictionary, it always return nil. How can I modify this method.

6
  • What is the error? Commented Apr 4, 2016 at 4:30
  • @BlakeLockley the guard statement used to define the endpoint give me error. I don't know how to resolve it Commented Apr 4, 2016 at 4:32
  • Maybe your url path is in a wrong format? Can you share with us? Commented Apr 4, 2016 at 4:34
  • @J.Wang Sorry dude. I don't have permission to do it Commented Apr 4, 2016 at 4:39
  • So when you say the guard statement gave you error, what error is this? Does it happen during runtime or compile time? And is the url a local file url or a remote url? Commented Apr 4, 2016 at 4:41

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.