使用Afnetworking发布没有图像的数据

时间:2014-09-21 04:58:55

标签: ios objective-c post afnetworking

我想将用户信息上传到服务器。它包含用户头像和用户个人资料数据。现在的问题是用户不会上传头像,所以我想过滤图像,如果用户没有上传它,那么任何人都可以帮我吗?

现在我正在使用此代码上传图片,它工作正常但我想上传即使用户没有上传图片

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
        NSData *imageData = UIImagePNGRepresentation(image);
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
        [Util showAlertDialog: NSLocalizedString(@"Success", nil):NSLocalizedString(@"Upload Successful", nil)];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure %@, %@", error, operation.responseString);
        [ Util showAlertDialog: NSLocalizedString(@"Failed", nil):NSLocalizedString(@"Upload Failed, Please try again", nil)];
    }];

1 个答案:

答案 0 :(得分:0)

我通过发送空的NSData

来解决这个问题
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:BASE_URL]];
        NSData *imageData;
        CGImageRef cgref = [image CGImage];
        CIImage *cim = [image CIImage];

        if (cim == nil && cgref == NULL)
        {
            imageData = [[NSData alloc] init];
        }else{
            imageData = UIImagePNGRepresentation(image);
        }

        [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
        [MBProgressHUD hideHUDForView:view animated:YES];
        [Util showAlertDialog: NSLocalizedString(@"Success", nil):NSLocalizedString(@"Upload Successful", nil)];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure %@, %@", error, operation.responseString);
        [MBProgressHUD hideHUDForView:view animated:YES];
        [ Util showAlertDialog: NSLocalizedString(@"Failed", nil):NSLocalizedString(@"Upload Failed, Please try again", nil)];
    }];