【问题标题】:AFNetworking: getPath:parameters-method causes an issueAFNetworking:getPath:parameters-method 导致问题
【发布时间】:2013-04-14 20:22:37
【问题描述】:

我正在尝试使用 AFNetworking(伟大的框架)向我的 Web 服务发出 GET 请求。这是请求的代码:

   AFHTTPClient *httpClient = [[AFHTTPClient alloc]initWithBaseURL:[NSURL URLWithString:@"http://mywebservice.com/service/"]];

[httpClient setParameterEncoding:AFJSONParameterEncoding];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

NSMutableURLRequest *request = [httpClient getPath:@"http://mywebservice.com/service/contacts"
parameters:@{@"accessID":self.accessId, @"name":contactName}
success:^(AFHTTPRequestOperation *operation, id responseObject) {
    //Success code
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //Error code
}];

这会导致出现以下问题(指向我的 NSMutableURLRequest 实例): 使用不兼容类型“void”的表达式初始化“NSMutableURLRequest *__strong”

我不知道是什么原因造成的,因此我们将不胜感激。

【问题讨论】:

    标签: ios objective-c json afnetworking


    【解决方案1】:

    AFHTTPClient上的这个方法:

    -(void)getPath:parameters:success:failure:
    

    什么都不返回 (void) 并且您正试图将它分配给一个变量。

    NSMutableURLRequest *request = [httpClient getPath:....
    

    这是我们解释您的错误消息所需的所有信息:

    Initializing 'NSMutableURLRequest *__strong' with an expression of incompatible type 'void'
    

    您声明了一个变量request,并将其键入为NSMutableURLRequest *。对于内存管理,ARC 添加了内存语义__strong。你的变量的完整类型是`NSMutableURLRequest *__strong。然后,您尝试将= 方法的结果分配给该变量-(void)getPath:parameters:success:failure:。该方法不返回任何内容,也称为voidvoidNSMutableRequest * 不是同一类型,所以编译器会报出上述错误消息。

    当你调用它时,这个方法实际上开始执行请求。结果作为参数提供给完成或失败块,在 HTTP 请求完成时执行。这将是执行您尝试发送的 HTTP 请求的正确方法:

    [httpClient getPath:@"contacts"
             parameters:@{@"accessID":self.accessId, @"name":contactName}
                success:^(AFHTTPRequestOperation *operation, id responseObject) {
                     //Success code
             } 
                failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                     //Error code
             }];
    

    注意它是如何没有分配给变量的。同样,当在AFHTTPClient 上使用这些路径方法时,我们不需要包含baseURL,只需要包含我们想要附加到它的路径部分。

    【讨论】:

    • 哦,不要介意 //Success 代码部分,我实际上有一些代码,但我认为这并不重要。 NSDictionary dictionary = (NSDictionary) responseObject;
    • 这并不重要。您误解了如何在AFHTTPClient 上使用此方法。我已经更新了答案
    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2011-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多