变量保持返回nil - Swift iOS

时间:2015-08-24 20:24:38

标签: swift alamofire

我正在使用Alamofire来解析JSON数据。除了'var id:JSON?'之外,下面提到的代码中的一切工作正常。虽然变量很好但是它在一个点(底部)保持返回nil。我需要将此变量放在过滤器闭包中。

class GreetingObjectHandler {
    var greetings: [Greeting] = []
    var id: JSON? //this variable
    init(filename: String) {
        Alamofire.request(.GET, "http://localhost:2403/users/me")
            .responseJSON { (req, res, data, error) in
                if(error != nil) {
                    NSLog("Error: \(error)")
                }
                else {
                    var parse = JSON(data!)
                    self.id = parse["id"] //updating 
                    println(self.id) //it's fine here
                }
        }

        let filePath = NSURL(string: "http://localhost:2403/users")
        let jsonData = NSData(contentsOfURL:filePath!)
        let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)

        for (key: String, subJson: JSON) in json {

            var language:String?, link: String?, description:String?, greetingText: String?

            for (key1, value:JSON) in subJson {
                switch key1 {
                case "displayName": language = value.string
                case "id": link = value.string
                case "username": description = value.string
                case "mainSkill": greetingText = value.string
                default: break
                }
            }

            let greeting = Greeting(language: language, link: link, description: description, greetingText: greetingText)
            self.greetings.append(greeting)
            self.greetings = self.greetings.filter { $0.link != "\(self.id)"} //this filter
         println(self.id)   //returns nil
        }
    }

    func getGreetingsAsAnyObjects() -> [String: [AnyObject]]{

        return [Constant.GreetingOBJHandlerSectionKey: greetings.map { $0 as AnyObject }]
    }
}

1 个答案:

答案 0 :(得分:2)

我虽然人们的评论非常清楚地解释了你的问题但是我认为使用闭包来处理你的请求然后在完成处理程序中处理其余的东西可以帮助你组织代码,比如以下方式:

func getJSON(url: String, completionHandler: (json: JSON?, error: NSError?) -> ()) {

    Alamofire.request(.GET, url)
        .responseJSON { (req, res, data, error) in completionHandler(
            json: {

                if let d = data {
                    var parse = JSON(d)
                    return parse
                }

                return nil
            }(), error: error)
    }
}

然后您可以通过以下方式拨打init

init(filename: String) {

    self.getJSON("http://localhost:2403/users") { json, error in
        if(error != nil) {
            NSLog("Error: \(error)")
        }
        else {
            self.id = json["id"]

            let filePath = NSURL(string: "http://localhost:2403/users")
            let jsonData = NSData(contentsOfURL:filePath!)
            let json = JSON(data: jsonData!, options: NSJSONReadingOptions.AllowFragments, error: nil)

            for (key: String, subJson: JSON) in json {

              var language:String?, link: String?, description:String?, greetingText: String?

              for (key1, value:JSON) in subJson {
                switch key1 {
                case "displayName": language = value.string
                case "id": link = value.string
                case "username": description = value.string
                case "mainSkill": greetingText = value.string
                default: break
              }
            }

            let greeting = Greeting(language: language, link: link, description: description, greetingText: greetingText)
            self.greetings.append(greeting)
            self.greetings = self.greetings.filter { $0.link != "\(self.id)"} //this filter
            println(self.id)
        }
    }
} 

使用上面的代码,您可以使用闭包来确保您的请求已完成。

我希望这对你有所帮助。