AFNetworking POST方法调用

时间:2015-09-25 20:30:37

标签: ios objective-c afnetworking

我是AFNetworking的新手。如何执行以下

的成功和失败块
NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:@"1211" forKey:@"id"];
[rus setValue:@"33" forKey:@"man"];
    [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://mysite.co/service.php" rus];

执行上述代码片段后如何显示成功或失败。

3 个答案:

答案 0 :(得分:0)

requestWithMethod实际上并没有完成调用,它只返回一个NSMutableURLRequest。您需要接受该请求并进行AFHTTPRequestOperation。您可以在此对象上设置成功/失败块,然后运行start方法。

NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:@"1211" forKey:@"id"];
[rus setValue:@"33" forKey:@"man"];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:@"http://mysite.co/service.php" parameters:rus];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    //Code for failure
}];
[operation start];

所有这一切,您使用的是过时版本的AFNetworking吗?您引用的方法已弃用。

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
                             URLString:(NSString *)URLString
                            parameters:(id)parameters
                                 error:(NSError *__autoreleasing *)error

以上是正确的使用方法。你应该传入一个错误对象。

最后,使用AFNetworking 2.0完成您所做的更简单的方法如下:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Code for failure
}];

答案 1 :(得分:0)

试试这段代码:

NSMutableDictionary *rus = [[NSMutableDictionary alloc] init];
[rus setValue:@"1211" forKey:@"id"];
[rus setValue:@"33" forKey:@"man"];

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

答案 2 :(得分:0)

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:@"http://mysite.co/service.php" parameters:rus success:^(AFHTTPRequestOperation *operation, id responseObject) {
    // Code for success
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Code for failure
}];

github的AFNetworking文件

https://github.com/AFNetworking/AFNetworking