在Alamofire关闭回归Bool [英] Return Bool in Alamofire closure

查看:90
本文介绍了在Alamofire关闭回归Bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Swift 2和Xcode 7.1。

I use Swift 2 and Xcode 7.1.

我有一个连接我的用户的功能,但它会在我的数据库中用HTTP连接。我使用Alamofire执行此请求。我想知道,如果用户已连接,则从视图控制器。

I have a function who connect my users, but it will connect at my database with HTTP. I use Alamofire for execute this request. I want to know, from a view controller if the user is connected.

我的功能是连接在一个类中。我在ViewController中测试连接。
喜欢这个:

I have my function connect in a class. And i test connection in a ViewController. Like this :

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

    // ...

}

第一个解决方案:返回

这样做需要我的功能返回一个布尔值。
只有我不能使用退货。

To do so would require that my function returns a Boolean. Only I can not use 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
            }
    }

第二个解决方案:

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

I can also test if the user has been logged, but before testing, I must wait for the function have finished loading.

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

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

我更喜欢返回一个布尔值。它将促进处理。
您有解决方案吗?

I would prefer return a boolean. It will facilitate the processing. Do you have a solution ?

推荐答案

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

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

    // now perform request

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

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

You can then call it using:

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



< hr>

BTW,如果你的服务器真的在生成JSON,你可以使用 responseJSON 而不是 responseString ,进一步简化代码,无需 convertStringToDictionary


BTW, if your server is really generating JSON, you might use responseJSON rather than responseString, further streamlining the code and eliminating the need for convertStringToDictionary:

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

    // now perform request

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

如果你有编写自己的服务器代码来验证用户,只需确保设置正确的标头(因为 responseJSON 不仅为您进行JSON解析,而且作为其验证过程的一部分,它确保标题指定JSON正文;无论如何设置标题是一种好习惯。例如在PHP中,在 echo JSON之前,设置标题如下:

If you've written your own server code to authenticate the user, just make sure you set the right header (because responseJSON not only does the JSON parsing for you, but as part of its validation process, it makes sure that the header specifies JSON body; it's good practice to set the header, regardless). For example in PHP, before you echo the JSON, set the header like so:

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

这篇关于在Alamofire关闭回归Bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆