Afnetworking post数组

时间:2014-02-17 21:15:55

标签: objective-c afnetworking-2

我试图用数组作为帖子而不是字典发布。但是我收到了一个错误:

Incompatible pointer types sending NSMutableArray to parameter of type NSDictionary

这是代码

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = @[@"foo", @"bar"];
[manager POST:@"http://example.com/resources.json" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

如何发布JUST数组内容?

更新

这段代码有效,但我希望得到以下答案,因为它的清洁和af处理序列化。我猜测请求体是不同的,但我怎么看到身体是什么?

  NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    NSString *body = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];


    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://example.com/resources.json"]
                                                           cachePolicy:NSURLRequestReloadIgnoringCacheData  timeoutInterval:10];

    [request setHTTPMethod:@"POST"];
    [request setValue: @"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];

    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"JSON responseObject: %@ ",responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", [error localizedDescription]);

    }];
    [op start];

1 个答案:

答案 0 :(得分:1)

我假设您希望foobar成为没有任何值的参数?如果是这样你会想要做这样的事情

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableArray *parameters = @[@"foo", @"bar"];
NSDictionary *params = [[NSDictionary alloc] initWithObjects:@[[NSNull null], [NSNull null]] forKeys:parameters];
[manager POST:@"http://example.com/resources.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

修改 尝试添加

manager.requestSerializer = [AFJSONRequestSerializer serializer];
manager.responseSerializer = [AFJSONResponseSerializer serializer];