SHRIMP
SHRIMP

Reputation: 147

Migrating from Objective-C to Swift : AFNetworking > Alamofire

I'm trying to migrate a project from Obj-C to Swift but got stuck at this part:

Objective-C:

-(void) novoLogin:(NSDictionary *) parametros completionBlock:(void(^)(BOOL sucesso, NSDictionary *retorno)) completion {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
    [manager GET:url parameters:parametros success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Retorno:\n%@", responseObject);        
        if([responseObject isKindOfClass:[NSString class]]) {
            responseObject = [self dictionaryFromString:responseObject];
        }

        NSString *error = responseObject[@"error"];
        completion(error == nil, responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", operation.responseString);
        completion(NO, @{@"error" : operation.responseString});
    }];
}

This is my draft implementation in Swift so far:

func doLogin(parameters: NSDictionary, completionHandler: (success: Bool, result: AnyObject?) -> Void) {

    guard let url = apiController.createURLWithComponentsForLogin() else {
      print("Invalid URL!")
      return
    }

    print(url)
    print("doLogin")

    alamofireManager.request(.GET, url, parameters: parameters as? [String : AnyObject], encoding: .URL).responseJSON {
      (response) in
      print(response.request)
      print(response.response)
      print(response.data)
      print(response.result.value)

      if let JSON = response.result.value {
        print("JSON result \(JSON)")
      }

      completionHandler(success: true, result: response.result.value)
    }
  }

It connects to a PHP webservice, I provide an email and password as parameters and expect to get back a json with {"user_id":"424230"} if succeeds or {"error":"Invalid data"} if fails.

This is the response i get from this test:

Optional(<NSMutableURLRequest: 0x7a65ff70> { URL: http://<hidden>/ws/index.php?r=webservice/ouvintes/login&email=awebmobile%40test.com&senha=123321 })

Optional(<NSHTTPURLResponse: 0x7a8bf8a0> { URL: http://<hidden>/ws/index.php?r=webservice/ouvintes/login&email=awebmobile%2540test.com&senha=123321 } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Encoding" = gzip;
    "Content-Length" = 51;
    "Content-Type" = "text/html";
    Date = "Wed, 20 Apr 2016 12:36:44 GMT";
    "Keep-Alive" = "timeout=5, max=100";
    Server = Apache;
    Vary = "Accept-Encoding";
} })

Optional(<7b226572 726f7222 3a224461 646f7320 496e765c 75303065 316c6964 6f732e22 7d>)

Optional({
    error = "Invalid data";
})

I provided the correct email and password... Why cant I get the valid {"id":"123456"} response? What am I missing here?

Upvotes: 1

Views: 1184

Answers (1)

Igor B.
Igor B.

Reputation: 2229

Try to encode parameters:

encodedEmail = emailString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())

Upvotes: 1

Related Questions