在Swift 2中没有在闭包内赋值的类属性

时间:2015-11-06 20:09:06

标签: ios swift

我无法为Swift类中的属性赋值。该属性在类中打印出来,但在调用在主viewController中分配属性的类方法时从外部访问时返回nil。这是我的班级定义。

import Foundation

class NetworkConnection {

    var jsonObj: AnyObject?

    func makeHTTPRequest(data: String, location: String, completion: (jsonData: AnyObject?, error: NSError?) -> Void){

        var jsonData: AnyObject!

        let post: NSString = "data=\(data)"
        let url = NSURL(string: location)!
        let postData = post.dataUsingEncoding(NSUTF8StringEncoding)!

        let postLength = String(postData.length)
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"
        request.HTTPBody = postData
        request.setValue(postLength, forHTTPHeaderField: "Content-Length")
        request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")

        let session = NSURLSession.sharedSession()

        let task = session.dataTaskWithRequest(request) { urlData, response, responseError in

            if let receiveData = urlData {

                let res = response as! NSHTTPURLResponse!

                if 200..<300 ~= res.statusCode {
                    do {
                        jsonData = try NSJSONSerialization.JSONObjectWithData(receiveData, options: NSJSONReadingOptions.init(rawValue:0))

                        completion(jsonData: jsonData, error: nil)
                    } catch let error as NSError {
                        let returnedError = NSError(domain: "validateUser", code: 3, userInfo: [
                            "title": "Made up title",
                            "message": "This is a messsage",
                            "cause": error
                            ])
                        completion(jsonData: nil, error: returnedError)
                    }
                }else{
                    let returnedError = NSError(domain: "validateUser", code: 1, userInfo: [
                        "title": "Second made up title",
                        "message": "This is another message"
                        ])
                    completion(jsonData: nil, error: returnedError)
                }
            }else{

                var userInfo: [NSObject: AnyObject] = [
                    "title": "Third made up title",
                    "message": "This is yet another message"
                ]
                if let error = responseError {
                    userInfo["message"] = error.localizedDescription
                    userInfo["cause"] = error
                }
                let returnedError = NSError(domain: "validateUser", code: 2, userInfo: userInfo)
                completion(jsonData: nil, error: returnedError)
            }


        }
        task.resume()

    }

    func validateUser(location: String, username: String, password: String) {

        let data = "&username=\(username)&password=\(password)"

        self.makeHTTPRequest(data, location: location) { jsonData, error in

            if let json = jsonData {

                self.jsonObj = json


                print(self.jsonObj)   // This shows property was assigned without errors

            }else{
                let userInfo = error!.userInfo
                let title = userInfo["title"] as! String
                let message = userInfo["message"] as! String
                print(title)
                print(message)
            }
        }
    }
}

这是我在viewController中调用validatUser()方法的函数

@IBAction func login(sender: AnyObject) {

        let service = NetworkConnection()
        service.validateUser("http://myPhpServiceLink.com/mobile.login.php", username: usernameField.text!, password: passwordField.text!)

        if let serviceObj = service.jsonObj {

            print("success loading object \(serviceObj)")

        } else {

            print("error loading object from call \(service.jsonObj)")

        }
}

以下是PHP返回的JSON数据。

{"id":"1","username":"admin","message":"User is valid","error":null}

行:print("service object = \(self.jsonObj)") 在控制台中打印出以下内容:

service object = Optional({
     error = "<null>";
     id = 1;
     message = "User is valid";
     username = admin;
})

但是我从@IBAction函数中得到了“来自调用nil的错误加载对象”。我到处寻找,以找出为什么财产在外部调用时总是返回nil并且很难说明我的问题。

1 个答案:

答案 0 :(得分:1)

我敢打赌这是因为你的http请求是在后台执行的。
if let serviceObj = service.jsonObj方法完成之前,validateUser正在执行。你需要重写`valdiateUser来获取一个完成处理程序。