objective-c - NSURLSessionTask 的 AFNetworking 1.x 到 3.x 迁移?

标签 objective-c ios9 xcode7 nsurlsession afnetworking-3

我有一个旧项目无法在 iOS 9 中运行。我已阅读 AFNetworking 的官方文档并完成了大部分迁移。

网络管理器:

_requestManager = [[AFHTTPSessionManager alloc]initWithBaseURL:[NSURL URLWithString:baseURL ]];
//here we can set the request header as the access token once we have logged in.
AFHTTPRequestSerializer *requestSerializer = [AFHTTPRequestSerializer serializer];
AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
[_requestManager setRequestSerializer:requestSerializer];
[_requestManager setResponseSerializer:responseSerializer];

早期版本:

// 2. Create an `NSMutableURLRequest`.
NSMutableURLRequest *request =
    [[NetworkManager sharedInstance].requestManager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:fullPath
                                                                                          parameters:nil
                                                                           constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
    NSString *fileName = [NSString stringWithFormat:@"%@.caf", theAudioItem.media_item_name];
    [formData appendPartWithFileData:audioData name:theAudioItem.media_item_name fileName:fileName mimeType:@"audio/caf"];
}];

// 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
AFHTTPRequestOperation *operation =
    [[NetworkManager sharedInstance].requestManager HTTPRequestOperationWithRequest:request
                                                                            success: ^(AFHTTPRequestOperation *operation, id responseObject) {
    result(YES, @"");
} failure: ^(AFHTTPRequestOperation *operation, NSError *error) {
    if (operation.responseData) {
        NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];

        result(NO, [responseDict valueForKey:@"Message"]);
        [self deleteTmpFilesFromParts:formParts];
    } else {
        result(NO, [NSString stringWithFormat:@"Failed to upload media to %@!", gallery.gallery_name]);
        [self deleteTmpFilesFromParts:formParts];
    }


    result(NO, errorMessage);
}];

// 4. Set the progress block of the operation.
[operation setUploadProgressBlock: ^(NSUInteger __unused bytesWritten,
                                     long long totalBytesWritten,
                                     long long totalBytesExpectedToWrite) {
    DLog(@"progress is %i %lld %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
    progress((float)totalBytesWritten / (float)totalBytesExpectedToWrite);
}];

// 5. Begin!
[operation start];

转换后的响应:(使用引发错误的注释进行更新)

//No visible @interface for 'AFHTTPRequestSerializer<AFURLRequestSerialization>' declares the selector 'multipartFormRequestWithMethod:URLString:parameters:constructingBodyWithBlock:'
    NSMutableURLRequest *request =
        [[NetworkManager sharedInstance].requestManager.requestSerializer multipartFormRequestWithMethod:@"POST" URLString:fullPath parameters:nil
                                                                               constructingBodyWithBlock: ^(id <AFMultipartFormData> formData) {
        NSString *fileName = [NSString stringWithFormat:@"%@.caf", theAudioItem.media_item_name];
        [formData appendPartWithFileData:audioData name:theAudioItem.media_item_name fileName:fileName mimeType:@"audio/caf"];
    }];

    // 3. Create and use `AFHTTPRequestOperationManager` to create an `AFHTTPRequestOperation` from the `NSMutableURLRequest` that we just created.
   //No visible @interface for 'AFHTTPSessionManager' declares the selector 'HTTPRequestOperationWithRequest:success:failure:'
    NSURLSessionTask *operation =
        [[NetworkManager sharedInstance].requestManager HTTPRequestOperationWithRequest:request
                                                                                success: ^(NSURLSessionTask *operation, id responseObject) {
        result(YES, @"");
    } failure: ^(NSURLSessionTask *operation, NSError *error) {

        //Error for operation doesn't have responseData
        if (operation.responseData) {
            NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:operation.responseData options:NSJSONReadingMutableContainers error:nil];

            result(NO, [responseDict valueForKey:@"Message"]);
            [self deleteTmpFilesFromParts:formParts];
        } else {
            result(NO, [NSString stringWithFormat:@"Failed to upload media to %@!", gallery.gallery_name]);
            [self deleteTmpFilesFromParts:formParts];
        }

        // get the response
        result(NO, errorMessage);
    }];

    // 4. Set the progress block of the operation.
    //No visible @interface for 'NSURLSessionTask' declares the selector 'setUploadProgressBlock:'
    [operation setUploadProgressBlock: ^(NSUInteger __unused bytesWritten,
                                         long long totalBytesWritten,
                                         long long totalBytesExpectedToWrite) {
        DLog(@"progress is %i %lld %lld", bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
        progress((float)totalBytesWritten / (float)totalBytesExpectedToWrite);
    }];

    // 5. Begin!
    //No visible @interface for 'NSURLSessionTask' declares the selector 'start'
    [operation start];

最佳答案

AFHTTPSessionManager的等效代码很简单:

NSURLSessionTask *task = [[[NetworkManager sharedInstance] requestManager] POST:fullPath parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    NSString *fileName = [NSString stringWithFormat:@"%@.caf", theAudioItem.media_item_name];
    [formData appendPartWithFileData:audioData name:theAudioItem.media_item_name fileName:fileName mimeType:@"audio/caf"];
} progress:^(NSProgress * _Nonnull uploadProgress) {
    NSLog(@"%.3f", uploadProgress.fractionCompleted);
} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    // success
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    // failure

    // if you need to process the `NSData` associated with this error (if any), you'd do:

    NSData *data = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
    if (data) { ... }
}];

与 v1.x 代码相比,这有两个主要变化:首先,在 2.x 中,他们引入了 GET/POST/etc。方法使您免于手动启动操作(或将其添加到您自己的队列中)。其次,在 3.x 中,他们退休了 AFHTTPRequestOperationManagerNSOperation 框架,现在使用 AFHTTPSessionManager 类,其中 GET/POST/etc。不返回 NSOperation 子类,而是返回 NSURLSessionTask 引用。

关于objective-c - NSURLSessionTask 的 AFNetworking 1.x 到 3.x 迁移?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35335804/

相关文章:

ios - 批准后 App Store 不显示我的更新版本

ios - 如何通过长按按钮然后拖动来移动 UIView?

ios - Xcode 7 升级后缺少适用于 IOS 的 Qt Creator 构建工具包

mysql - 从 XML Paradox 导入 CoreData

ios - 从未收到 GKMatchmaker findMatchForRequest 邀请

IOS 9 Ipad kCFStreamErrorDomainSSL, -9802,如何解决这个问题?

ios - ALAsssetsLibrary 的 assetForURL :resultBlock:failure in Photos Framework? 的等效方法是什么

ios - UIButton高亮显示的图像未显示

ios - 如何正确释放没有句柄的分配对象

objective-c - 链接到 objective-c 项目中的可执行文件