从Objective-C迁移到Swift:AFNetworking> Alamofire

时间:2016-04-20 12:59:00

标签: ios objective-c swift afnetworking alamofire

我正在尝试将项目从Obj-C迁移到Swift,但却被困在这一部分:

目标-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});
    }];
}

到目前为止,这是我在Swift中的草案实现:

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

它连接到PHP Web服务,我提供了一个电子邮件和密码作为参数,如果成功或者{“错误”:“无效数据”},如果失败,我希望用{“user_id”:“424230”}取回json

这是我从这次测试中得到的回应:

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

我提供了正确的电子邮件和密码...为什么我无法获得有效的{“id”:“123456”}回复?我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

尝试编码参数:

encodedEmail = emailString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())