ios - AFNetworking:getPath:参数方法导致问题

标签 ios objective-c json afnetworking

我正在尝试使用 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”

我不知道是什么原因造成的,所以任何帮助将不胜感激。

最佳答案

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 * 不是同一类型,因此编译器会提示上述错误消息。

当您调用此方法时,它实际上开始执行请求。结果作为参数提供给完成或失败 block ,它们在 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
         }];

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

关于ios - AFNetworking:getPath:参数方法导致问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16003925/

相关文章:

ios - numberFromString 的 NSNumberFormatter 问题

ios - 我们如何在自定义 UIView 类中调用操作?需要在所有 View Controller 中重用 UIView 类

ios - 在我的 Objective-C 项目中进行 Swift 类集成后,无法在设备上进行编译

ios - 将 iOS 键盘布局更改为表情符号?

ios - Touch Down 不执行它应该执行的操作

iOS SDK 5.0(xcode 4.x)

c# - 解码 Base64 和 Inflate Zlib 压缩 XML

ios - Swift CodeUnit 到 String

ios - 如何在 swift 3 中创建一个 json 对象通过 POST api 发送它?

php - json_encode 添加双引号而不是空格