从swift中的do-catch语句中获取变量

时间:2016-01-07 04:53:04

标签: swift uitableview asynchronous do-catch

我想知道如何使用保留在do-catch语句中的变量。我正在从Web解析一些JSON并用它填充一个对象但是我需要外面的那个对象来填充UITableView。我获取网络信息的功能:

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
}

所以,我调用函数并在里面执行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!)

                    }

现在可以使用JSON_Info吗?如果没有,即使采用其他变量就足够了,所以我可以从函数中执行for循环。理想情况下,我想在函数中使用infoArray和infoArrayDB。感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

首先创建对象声明类:

  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!)

                }

现在您可以查看您想要用户的任何地方

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

}

答案 1 :(得分:1)

您在do/catch之前声明它们,并在之后使用它们,前提是您将它​​们声明为可选项,并在catch中为它们提供值:

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

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

let允许你稍后进行赋值,所以我们可以使用它,不要将两者保持为常量(Swift方式)。

请注意,如果您想使用它们,则需要打开它们,这有点重复您在do/catch内的努力。