Alamofire封闭中的返回布尔

问题描述 投票:5回答:3

我使用Swift 2和Xcode 7.1。

我有一个连接用户的功能,但是它将通过HTTP在我的数据库上连接。我使用Alamofire执行此请求。我想从视图控制器知道用户是否已连接。

我将函数连接到类中。我在ViewController中测试连接。像这样:

    class user {

    // ...

    func connectUser(username: String, password: String){

        let urlHost = "http://localhost:8888/project350705/web/app_dev.php/API/connect/"
        let parametersSymfonyG = [
            username, password
        ]
        let url = UrlConstruct(urlHost: urlHost).setSymfonyParam(parametersSymfonyG).getUrl()

        //var userArray = [String:AnyObject]()

        Alamofire.request(.GET, url)
            .responseString { response in

                if let JSON = response.result.value {

                    var result = self.convertStringToDictionary(JSON)!

                    if result["status"] as! String == "success"{
                        let userArray = result["user"] as! [String:AnyObject]
                        userConnect = self.saveUser(userArray)
                    } else{
                        print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
                    }
                    return ""
                }
        }
    }

    // ...
}

class MyViewController: UIViewController {

    // ...

    @IBAction func connect(sender: AnyObject?) {

        // CONNECTION
        User.connectUser(self.username.text!, password: self.password.text!)

        // CHECK
        if userConnect != nil {
            print("connected")
        }else{
            print("NotConnected")
        }
    }

    // ...

}

第一个解决方案:返回

为此,我的函数必须返回布尔值。只有我不能使用return。

Alamofire.request(.GET, url)
        .responseString { response in

            if let JSON = response.result.value {

                var result = self.convertStringToDictionary(JSON)!

                if result["status"] as! String == "success"{
                    let userArray = result["user"] as! [String:AnyObject]
                    userConnect = self.saveUser(userArray)
                } else{
                    print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
                }
                return "" // Unexpected non-void return value in void function
            }
    }

第二解决方案:

我还可以测试用户是否已经登录,但是在测试之前,我必须等待函数完成加载。

users.connectUser(self.username.text!, password: self.password.text!)

// after 
if userConnect != nil {
    print("connected")
}else{
    print("NotConnected")
}

我希望返回一个布尔值。这将有助于处理。您有解决方案吗?

ios xcode swift alamofire
3个回答
12
投票

我建议在您的connectUser方法中使用完成处理程序:

func connectUser(username: String, password: String, completion: @escaping (Bool) -> Void) {
    // build the URL

    // now perform request

    Alamofire.request(url)
        .responseString { response in
            if let json = response.result.value, let result = self.convertStringToDictionary(json) {
                completion(result["status"] as? String == "success")
            } else {
                completion(false)
            }
    }
}

然后您可以使用以下方式调用它:

users.connectUser(username.text!, password: password.text!) { success in
    if success {
        print("successful")
    } else {
        print("not successful")
    }
}
// But don't user `success` here yet, because the above runs asynchronously

顺便说一句,如果您的服务器确实在生成JSON,则可以使用responseJSON而不是responseString,从而进一步简化代码并消除对convertStringToDictionary的需要:

func connectUser(username: String, password: String, completion: @escaping (Bool) -> Void) {
    // build the URL

    // now perform request

    Alamofire.request(url)
        .responseJSON { response in
            if let dictionary = response.result.value as? [String: Any], let status = dictionary["status"] as? String {
                completion(status == "success")
            } else {
                completion(false)
            }
    }
}

如果您编写了自己的服务器代码来验证用户身份,则只需确保设置正确的标头即可(因为responseJSON不仅会为您解析JSON,而且作为其验证过程的一部分,请确保标头指定JSON正文;无论如何,设置标头都是一个好习惯。例如,在PHP中,在echo JSON之前,像这样设置标头:

header("Content-Type: application/json");

2
投票

Alamofire.request方法的完成处理程序是异步的,并且在其签名中没有指定返回类型。这就是为什么在完成处理程序闭包中提供return语句时看到错误的原因。

您将必须将请求和响应处理拆分为单独的方法,然后调用响应处理方法,而不要使用return语句。

Alamofire.request(.GET, url).responseString { response in

        if let JSON = response.result.value {
            var result = self.convertStringToDictionary(JSON)!

            if result["status"] as! String == "success"{
                let userArray = result["user"] as! [String:AnyObject]
                userConnect = self.saveUser(userArray)
                processSuccessResponse() //Pass any parameter if needed
            } else{
                print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
                processFailureResponse() //Pass any parameter if needed
            }
       }
}

func processSuccessResponse() {
    //Process code for success
}

func processFailureResponse() {
    //Process code for failure
}

1
投票

我这样做的首选方式是在完成处理程序中调用一个函数。您还可以设置一个布尔值标志,以便在任何给定时间检查用户是否已连接。

func connectUser(username: String, password: String, ref: MyClass) {
    Alamofire.request(.GET, url)
        .responseString { response in

            var userIsConnected = false

            if let JSON = response.result.value {

                var result = self.convertStringToDictionary(JSON)!

                if result["status"] as! String == "success"{
                    let userArray = result["user"] as! [String:AnyObject]
                    userConnect = self.saveUser(userArray)
                    userIsConnected = true
                } else {
                    print("ERROR-CONNECTION :\n Status :\(result["status"]!)\n Code :\(result["code"]!)")
                }

            } else {
                print("Response result nil")
            }

            ref.finishedConnecting(userIsConnected)
        }
    }
}

class MyClass {
    var userIsConnected = false

    func startConnecting() {
        connectUser(username, password: password, ref: self)
    }

    func finishedConnecting(success: Bool) {
        userIsConnected = success

        ... post-connection code here
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.