Variable keeps returning nil - Swift iOS

 ̄綄美尐妖づ 提交于 2019-12-13 09:08:28

问题


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

回答1:


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.




回答2:


Alamofire requests run asynchronously, so the println statement at the end of the init function runs before the println statement at the end of the responseJSON closure. A fix for this would be to run the code that requires the json variable inside the responseJSON closure.




回答3:


All your suggestions were valid but this is what actually worked.

import Foundation
import Alamofire

class GreetingObjectHandler {
    var greetings: [Greeting] = []

    init(filename: String) {

        let fileP = NSURL(string: "http://localhost:2403/users/me")
        let jsonD = NSData(contentsOfURL:fileP!)
        let jso = JSON(data: jsonD!, options: NSJSONReadingOptions.AllowFragments, error: nil)
        var id = jso["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 != "\(id)"}
        }
    }

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

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


来源:https://stackoverflow.com/questions/32191127/variable-keeps-returning-nil-swift-ios

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!