SWIFT 2全局变量不包含任何数据。在范围内有数据。

时间:2016-03-18 02:07:23

标签: swift

  

全局变量不包含任何数据。在范围内有数据。 NSLog告诉我,函数GetJsonDataFromURL中的数据包含数据。

'请向我解释为什么以及什么是行业标准的处理变量和数据的方法已经调试了几天'

var employeeData : Dictionary<String, AnyObject> = [:]
override func viewDidLoad() {
    super.viewDidLoad()
    GetJsonDataFromURL()
    NSLog("%@", employeeData) <- THIS LINE HAS NO DATA
}

func GetJsonDataFromURL() {

    let postEndpoint: String = "http://localhost/watsdis/showOutbox.php"
    let session = NSURLSession.sharedSession()
    let url = NSURL(string: postEndpoint)!
    var dataContainer : Dictionary <String, String> = [:]
    var mobiles : Dictionary <String, String> = [:]
    var msgs : Dictionary <String, String> = [:]
    var ids : [String] = []
    var names : Dictionary <String, String> = [:]
    var pos = ""
    // Make the POST call and handle it in a completion handler
    session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, let error: NSError?) -> Void in
        // Make sure we get an OK response
        guard let realResponse = response as? NSHTTPURLResponse where
                  realResponse.statusCode == 200 else {
            print("Not a 200 response")
                    return
        }

        // Read the JSON
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
            if let employees = json["employee"] as? [[String: AnyObject]] {
                for employee in employees {
                    if let id = employee["id"] as? String {
                        ids.append (id)
                        pos = id
                    }
                    if let mobile = employee["mobile"] as? String {
                        mobiles[pos] = mobile
                    }
                    if let msg = employee["msg"] as? String {
                        msgs[pos] = msg
                    }
                    if let name = employee["name"] as? String {
                        names[pos] = name
                    }

                }
            }
            self.employeeData["id"] = ids
            self.employeeData["name"] = names
            self.employeeData["mobile"] = mobiles
            self.employeeData["msg"] = msgs
       } catch {
            print("error serializing JSON: \(error)")
        }
        NSLog("%@", self.employeeData) <- THIS LINE DISPLAYS MY DATA IN ARRAY FORMAT
    }).resume();
}

2 个答案:

答案 0 :(得分:0)

您正在使用回调调用异步方法。在将数据放入employeeData的回调之前,您很有可能检查变量。

答案 1 :(得分:0)

GetJsonDataFromURL是acsync功能 在viewDidLoad中你打电话:

GetJsonDataFromURL()
NSLog("%@", employeeData) <- THIS LINE HAS NO DATA

NSLog在函数GetJsonDataFromURL返回数据之前运行,因此它为空数据。 你试试:

func GetJsonDataFromURL(handleComplete:(isOK:Bool)->()) {

    let postEndpoint: String = "http://localhost/watsdis/showOutbox.php"
    let session = NSURLSession.sharedSession()
    let url = NSURL(string: postEndpoint)!
    var dataContainer : Dictionary <String, String> = [:]
    var mobiles : Dictionary <String, String> = [:]
    var msgs : Dictionary <String, String> = [:]
    var ids : [String] = []
    var names : Dictionary <String, String> = [:]
    var pos = ""
    // Make the POST call and handle it in a completion handler
    session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, let error: NSError?) -> Void in
        // Make sure we get an OK response
        guard let realResponse = response as? NSHTTPURLResponse where
            realResponse.statusCode == 200 else {
                print("Not a 200 response")
                return
        }

        // Read the JSON
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
            if let employees = json["employee"] as? [[String: AnyObject]] {
                for employee in employees {
                    if let id = employee["id"] as? String {
                        ids.append (id)
                        pos = id
                    }
                    if let mobile = employee["mobile"] as? String {
                        mobiles[pos] = mobile
                    }
                    if let msg = employee["msg"] as? String {
                        msgs[pos] = msg
                    }
                    if let name = employee["name"] as? String {
                        names[pos] = name
                    }

                }
            }
            self.employeeData["id"] = ids
            self.employeeData["name"] = names
            self.employeeData["mobile"] = mobiles
            self.employeeData["msg"] = msgs
            handleComplete(isOK: true)
        } catch {
            handleComplete(isOK: false)
            print("error serializing JSON: \(error)")
        }
        NSLog("%@", self.employeeData) <- THIS LINE DISPLAYS MY DATA IN ARRAY FORMAT
    }).resume();
}

并在viewDidLoad

self.GetJsonDataFromURL { (isOK) -> () in
        if isOK{
            print(self.employeeData)
        }else{
            print("error")
        }
    }