obj-c AFNetworking 2.0 POST请求不起作用

jer*_*rik 9 post objective-c request ios afnetworking-2

您想通过使用AFNetworking 2.0将一些数据(字符串和文件)发送到服务器.不知何故,POST请求(对于forumlar)的数据不正确,看起来缺少请求的编码/序列化.由于服务器无法使用我上传的数据.

如何为请求设置编码/序列化?

我假设必须设置URL表单参数编码.文档说明

[[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];
Run Code Online (Sandbox Code Playgroud)

我试图这样做,但我无法弄清楚如何正确地做到这一点.通过以下Xcode通过警告:

manager.requestSerializer = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters]; 
Run Code Online (Sandbox Code Playgroud)

/.../CameraViewController.m:105:31:从'NSMutableURLRequest*'分配给'AFHTTPRequestSerializer*'的指针类型不兼容

在我的源代码下面:

CameraViewController.h

#import <UIKit/UIKit.h>

@interface CameraViewController : UIViewController <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *imageView;

@end
Run Code Online (Sandbox Code Playgroud)

CameraViewControllerView.m

#import "CameraViewController.h"
#import "AFHTTPRequestOperationManager.h"

@interface CameraViewController ()    
@property (nonatomic) int photoIsTaken;    
@end

@implementation CameraViewController

// removed unecessary code for this question

- (void)upload {
    NSLog(@"%s: uploader ", __FUNCTION__);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSDictionary *parameters = @{@"latitude": @"8.444444",
                                 @"longitude": @"50.44444",
                                 @"location": @"New York",
                                 @"type": @"2",
                                 @"claim": @"NYC",
                                 @"flag": @"0",
                                 @"file": UIImageJPEGRepresentation(self.imageView.image,0.2)};

NSString *URLString = @"http://192.168.1.157/tapp/laravel/public/foobar/upload";

manager.requestSerializer = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:URLString parameters:parameters];

[manager POST:URLString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@, %@", error, operation.responseString);
}];

    [self dismissViewControllerAnimated:NO completion:nil];
}

@end
Run Code Online (Sandbox Code Playgroud)

jer*_*rik 6

最后它有效.麻烦但现在我真的很开心......在我测试期间,我在Wifi内遇到了"请求身体流消耗"的问题,这很奇怪.

下面代码为我做了诀窍.

- (void)upload {

    // !!! only JPG, PNG not covered! Have to cover PNG as well
    NSString *fileName = [NSString stringWithFormat:@"%ld%c%c.jpg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];
    // NSLog(@"FileName == %@", fileName);

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    NSDictionary *parameters = @{@"lat": @"8.444444",
                                 @"lng": @"50.44444",
                                 @"location": @"New York",
                                 @"type": @"2",
                                 @"claim": @"NYC",
                                 @"flag": @"0"};
     // BASIC AUTH (if you need):
    manager.securityPolicy.allowInvalidCertificates = YES;
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"foo" password:@"bar"];
    // BASIC AUTH END

    NSString *URLString = @"http://192.168.1.157/tapp/laravel/public/foobar/upload";

    /// !!! only jpg, have to cover png as well
    NSData *imageData = UIImageJPEGRepresentation(self.imageView.image, 0.5); // image size ca. 50 KB
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success %@", responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure %@, %@", error, operation.responseString);
    }];

    [self dismissViewControllerAnimated:NO completion:nil];
}
Run Code Online (Sandbox Code Playgroud)


BB9*_*B9z 6

感谢@NobleK,类别可能是解决此问题的最佳方法.这是一个示例代码:

@interface AFURLConnectionOperation (AuthenticationChallengeUploadFix)
@end

@implementation AFURLConnectionOperation (AuthenticationChallengeUploadFix)

- (NSInputStream *)connection:(NSURLConnection __unused *)connection needNewBodyStream:(NSURLRequest *)request {
    if ([request.HTTPBodyStream conformsToProtocol:@protocol(NSCopying)]) {
        return [request.HTTPBodyStream copy];
    }
    return nil;
}

@end
Run Code Online (Sandbox Code Playgroud)