Bool Returns to Alamofire Closure

I am using Swift 2 and Xcode 7.1.

I have a function that connects my users, but it will connect in my database with HTTP. I am using Alamofire to fulfill this request. I want to know from the controller point of view if the user is connected.

I have a connect function in a class. And I am testing the connection in 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")
        }
    }

    // ...

}

First decision: Return

This will require my function to return a boolean value. Only I can not use the refund.

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

The second solution:

I can also check if the user has been registered, but before testing, I must wait for the function to load loaded.

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

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

I would prefer to return a boolean. This will facilitate handling. Do you have a solution?

+4
3

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

, :

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:(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 :

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

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
}
+2

My preferred way to do this is to call the function in the completion handler. You can also set a logical flag to check if the user is connected at any given time.

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
    }
}
+1
source

Source: https://habr.com/ru/post/1618806/


All Articles