Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
264 views
in Technique[技术] by (71.8m points)

alamofire - Variable keeps returning nil - Swift iOS

I'm using Alamofire to Parse JSON data. Everything is working fine in below mentioned code except 'var id: JSON?' variable though it's updating just fine but it keeps returning nil at a point (at bottom). I need to put this variable inside filter closure.

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 }]
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I though that the comments of the people explain very well what is your problems nevertheless I think that make a function to handle your request using closures and then handling in completion handler the rest can help you to organize your code, something like in the following way:

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

And then you can call in your init in the following way:

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

With the above code you make use of the closures to sure that your request is completed.

I hope this help you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...