将afnetworking post请求重构为3.0

时间:2016-04-05 13:14:23

标签: ios afnetworking afnetworking-3

我收到了警告:

Incompatible pointer types assigning to 'AFHTTPSessionManager *' from 'NSURLSessionDataTask * _Nullable'

'POST:parameters:success:failure:' is depreceated 

尝试使用AFNetworking 3.0发出请求时。我想知道使用iOS 7.0或更高版本的应用程序使用AFNewtworking 3.0发布请求的正确方法是什么。这是我的代码:

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setResponseSerializer:[SignupResponseSerializer serializer]];

    __weak typeof(self)weakSelf = self;

    NSString *urlString = [NSString stringWithFormat:@"%s%s", kBaseURL, kRegisterURL];

    NSData *plainData = UIImagePNGRepresentation(self.profilePicture);
    NSString *base64String = [plainData base64EncodedStringWithOptions:0];

    if (self.firstNameField.text && self.lastNameField.text && self.passwordField.text && self.emailField.text) {
        NSDictionary *params = @{ @"first_name": self.firstNameField.text, @"last_name": self.lastNameField.text, @"password": self.passwordField.text, @"email": self.emailField.text, @"avatar_data": base64String};

        self.sessionManager = [manager POST:urlString parameters:params success:^(NSURLSessionTask *task, id responseObject) {
            NSDictionary *JSON = [responseObject objectAtIndex:0];
            NSString *token = JSON[@"auth_token"];
            NSString *avatarURL = JSON[@"avatar_url"];


            weakSelf.credentialStore.avatarURL = avatarURL;
            weakSelf.credentialStore.authToken = token;
            weakSelf.credentialStore.firstName = self.firstNameField.text;
            weakSelf.credentialStore.lastName = self.lastNameField.text;
            weakSelf.credentialStore.email = self.emailField.text;
            weakSelf.credentialStore.password = self.passwordField.text;

            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:nil];
        } failure:^(NSURLSessionTask *task, NSError *error) {
//            if (task.isCancelled) {
//                return;
//            }
            [SVProgressHUD showErrorWithStatus:@"Login Failed"];
            NSLog(@"%@", error);
        }];
    }

1 个答案:

答案 0 :(得分:1)

在AFNetworking 3.0中,POST方法会根据您的请求返回NSURLSessionDataTask个对象。 此外,它现在有一个progress参数,它是一个用于跟踪请求进度的块。
所以我建议你改变方法调用:

self.sessionManager = [manager POST:urlString parameters:params success:^(NSURLSessionTask *task, id responseObject) {
...

到此:

//If you want a reference to the manager you can initialize the sessionManager var like this but it's not necessary
self.sessionManager = manager;
[manager POST:urlString parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        //progress block implementation
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //success block implementation
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //failure block implementation
    }];