Fehlerbehandlung in Alamofire

Habe ich den HTTP code in einem AngularJS controller:

$http.post('/api/users/authenticate', {email: $scope.email, password: $scope.password})
    .success(function (data, status, headers, config) {
        authService.login($scope.email);
        $state.go('home');
    })
    .error(function (data, status, headers, config) {
        $scope.errorMessages = data;
        $scope.password = "";
    });

In dem Fall Erfolg, der server antwortet mit einer JSON-Repräsentation eines Benutzers. Im Fehler-Fall wird der server antwortet mit einem einfachen string wie User not found zugegriffen werden kann durch die data parameter.

Ich habe Schwierigkeiten, herauszufinden, wie etwas zu tun, ähnlich wie in Alamofire. Hier ist, was ich jetzt haben:

@IBAction func LoginPressed(sender: AnyObject) {
    let params: Dictionary<String,AnyObject> = ["email": emailField.text, "password": passwordField.text]

    Alamofire.request(.POST, "http://localhost:3000/api/users/authenticate", parameters: params)
        .responseJSON {(request, response, data, error) in
            if error == nil {
                dispatch_async(dispatch_get_main_queue(), {
                    let welcome = self.storyboard?.instantiateViewControllerWithIdentifier("login") as UINavigationController;

                    self.presentViewController(welcome, animated: true, completion: nil);
                })
            }
            else{
                dispatch_async(dispatch_get_main_queue(), {
                    //I want to set the error label to the simple message which I know the server will return
                    self.errorLabel.text = "something went wrong"
                });
            }
    }
}

Ich habe keine Ahnung, ob ich Umgang mit der nicht-Fehler-Fall richtig und würde schätzen, Eingang.

InformationsquelleAutor Paymahn Moghadasian | 2015-03-13

Schreibe einen Kommentar