1

我想知道如何使用留在 do-catch 语句中的变量。我正在从网络解析一些 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。我感谢您的帮助。

4

2 回答 2

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

}

于 2016-01-07T06:27:52.790 回答
1

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

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

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

let允许您稍后进行分配,因此我们可以使用 this 不将两者保留为常量(Swift 方式)。

请注意,如果你想使用它们,你需要打开它们,这有点重复你从do/catch.

于 2016-01-07T07:09:35.260 回答