Search code examples
swiftuitableviewasynchronousdo-catch

Getting Variable out of do-catch statement in swift


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.


Solution

  • 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
    

    }