1

I'm using alamofire to get HTTP response from web api. just want to ask how can parse JSON values from response without using swift object mapper frameworks and pass it to authenticatedUser.I have some problem with loadUserData because response return Response type and my function work fine with NSArray how can I converted to work with Response

func GetUserCredential(username:String,password:String)->UserModel
 {
    let authenticatedUser  = UserModel()
    let user = username
    let password = password

    let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)

    Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
        .authenticate(usingCredential: credential)
        .responseJSON { response in
            return self.loadUserData(response);

    }

    return authenticatedUser;

 }

func loadUserData(response: Response<AnyObject, NSError>) -> UserModel
{
    var userObj = UserModel()
    for resp as? Response<AnyObject, NSError> in response
    {
        let user:String = (resp["user"] as! String)
        let isAuthenticated:Bool = (resp["authenticated"] as! Bool)
        let isManager:Bool = true

        userObj = UserModel(username:user,isAuthenticated:isAuthenticated,isManager:isManager)
    }
    return userObj
}
NinjaDeveloper
  • 1,620
  • 3
  • 19
  • 51

1 Answers1

4

I believe you can do this with an Alamofire response object.

if let validResponse = response.result.value as? [String : AnyObject] {
     return loadUserData(validResponse);
}

I would change your loadUserData to this:

func loadUserData(response: [String : AnyObject]) -> UserModel
    // Do everything you're doing in loadUserData
}

I would also do more error checking in your loadUserData method as it's best not to assume that user and authenticated will always exist (your app will crash if they don't or if their values are of different types).

I would also suggest you name GetUserCredential with a lowercase getUserCredential to keep in best practice for naming functions.

Xeaza
  • 1,410
  • 1
  • 17
  • 21