1

I want to know how to use a variable which is staying in a do-catch statement. I'm parsing some JSON from the web and filling an object with it but then I need that object outside to fill a UITableView. The function where I get web info:

func post(dburl: String, info: String, completionHandler: (NSString?, NSError?) -> ()) -> NSURLSessionTask {

let myUrl = NSURL(string: dburl)!;
let request = NSMutableURLRequest(URL:myUrl);
request.HTTPMethod = "POST";
let postString = info //finalPlaceId = info
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
    { data, response, error in dispatch_async(dispatch_get_main_queue()) {
        guard data != nil else {
            completionHandler(nil, error)
            return
        }
        completionHandler(NSString(data: data!, encoding: NSUTF8StringEncoding), nil)

        }
}
task.resume()
return task
}

So, I call the function and inside I do the do-catch:

post(dburl, info: finalPlaceId) { responseString , error in
                        guard responseString != nil else {
                            print(error)
                            return

                        }

                        do { if  let dataDB = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {

                            var error: NSError?
                            let jsonDB = try NSJSONSerialization.JSONObjectWithData(dataDB, options:[])

                            //print(jsonDB)

                            if let infoArray = jsonResults["results"] as? [NSDictionary] {

                                if let infoArrayDB = jsonDB as? [NSDictionary] {

                                    for item in infoArray {
                                            for item2 in infoArrayDB {

                                                self.JSON_Info.append(JSONInfo(json: item))
                                                self.JSON_Info.append(JSONInfo(json: item2))

                                    }
                                    }
                                    print(infoArrayDB)

                                }


                            }

                        }
                        } catch {                print("Fetch Failed:\(error as NSError).localizedDescription)")
}



                       // print(responseString!)

                    }

Is it possible to now use JSON_Info out of this function? If not, even taking the other variables would be enough so I could do the for loops out of the function. Ideally I'd like to use infoArray and infoArrayDB out of the function. I appreciate your help.

rmaddy
  • 314,917
  • 42
  • 532
  • 579
manhols
  • 25
  • 4

2 Answers2

1

First create object declaration class :

  var infoArray : [NSDictionary]?
  var infoArrayDB : [NSDictionary]?
  post(dburl, info: finalPlaceId) { responseString , error in
                    guard responseString != nil else {
                        print(error)
                        return

                    }

                    do { if  let dataDB = responseString!.dataUsingEncoding(NSUTF8StringEncoding) {

                        var error: NSError?
                        let jsonDB = try NSJSONSerialization.JSONObjectWithData(dataDB, options:[])

                        //print(jsonDB)

                        if let infoArray = jsonResults["results"] as? [NSDictionary] {
                        self.infoArray = infoArray
                            if let infoArrayDB = jsonDB as? [NSDictionary] {
                        self.infoArrayDB = infoArray
                                for item in infoArray {
                                        for item2 in infoArrayDB {

                                            self.JSON_Info.append(JSONInfo(json: item))
                                            self.JSON_Info.append(JSONInfo(json: item2))

                                }
                                }
                                print(infoArrayDB)

                            }


                        }

                    }
                    } catch {                print("Fetch Failed:\(error as NSError).localizedDescription)")
  }



                   // print(responseString!)

                }

Now you can check anywhere you want user

    if let infoArray = self.infoArray{
      /// Do whatever you want

}

Bhoomi Jagani
  • 2,413
  • 18
  • 24
  • If my answer resolve your problem then accept my answer.Thanks. – Bhoomi Jagani Jan 07 '16 at 11:33
  • Hi bhoomi one more question. Actually it worked perfectly out of the do-catch (which was the original question) but I still can't use it out of the function, I'm assuming it calls an async task? I need to fill a tableview with the information from the function but it's nil outside of it. What would you recommend? – manhols Jan 09 '16 at 04:16
  • Nevermind. I ended up doing a tableview.reloadData inside the function. Thanks again – manhols Jan 09 '16 at 06:18
1

You declare them before the do/catch, and use them afterwards, providing you declare them as optional, and you give them values also in the catch:

let infoArray : [NSDictionary]?
let infoArrayDB : [NSDictionary]?

do {
    // your code from above
} catch {
    infoArray = nil
    infoArrayDB = nil
}

let allow you to the assignment later, so we can use this no keep the two as constants (the Swift way).

Be aware that you'd need to unwrap them if you want to use them, which kinda duplicates you effort from inside the do/catch.

Cristik
  • 30,989
  • 25
  • 91
  • 127