AFNetworking:无法从AFHTTPRequestOperation获取响应字符串

时间:2012-12-11 00:43:07

标签: ios networking afnetworking nsurlrequest

任何人?):我遇到的问题让我在过去的2个小时里刮过头脑,这很可能是一个非常简单的愚蠢的事情。当我从操作@ AFNetworking调用响应字符串时,我继续收到建筑错误...就像没有这样的属性....

请看一下我的代码并解释一下我搞砸了这次:p ..谢谢:)


NSDictionary* paramDict = [NSDictionary dictionaryWithObjectsAndKeys:WebServicemd5Value, WebSermd5Variable, nil]
;
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:webServiceURL]];

[httpClient defaultValueForHeader:@"Accept"];

[httpClient postPath:@"method" parameters:paramDict success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"Response data: %@", responseObject);
    NSLog(@"Reponse String: %@", operation);

//打印操作将显示操作字典,包括响应字段,//但是当我直接调用operation.response时,编译器将不会构建,说明//“找不到AFHTTPRequestOperation的属性”.. .. WEIRDEST THING EVER,对吧?

    NSString* responseString = [NSString stringWithUTF8String:[responseObject bytes]];
    //.. Rest o f my Code....

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

3 个答案:

答案 0 :(得分:15)

Hernan,如果您希望JSON响应中有NSDictionary,则应考虑使用AFJSONRequestOperation,因为您在成功回调中获得了JSON字典。无论如何,如果您想从responseObject获取字典,请尝试使用以下代码:

NSError *error = nil;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:&error];
if (error) {
    NSLog(@"Error serializing %@", error);
}
NSLog(@"Dictionary %@", JSON);

答案 1 :(得分:5)

我认为响应字符串位于"操作"对象,所以像:

...
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error retrieving data: %@", operation.responseString);
}];

答案 2 :(得分:4)

尝试使用AFNetworking从meetup.com api检索内容时(对于一个伟大的框架,请向Mattt T.致敬,顺便说一句),遇到了同样的错误 - “操作无法完成。(Cocoa error 3840)” 。意识到我遇到的问题是包含瑞典字符“Ø”的响应数据,导致解析错误。解决方案是在AFNetworking客户端的初始化中包含标题'Accept-Charset:utf-8'。固定!

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];

    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    [self setDefaultHeader:@"Accept-Charset" value:@"utf-8"];

    return self;
}