setCompletionBlockWithSuccess无法正常工作

时间:2016-04-02 01:30:28

标签: objective-c afnetworking

我试图使用AFHTTPRequestOperation类从在线php文件中获取数据,但我遇到了一些麻烦。

NSString *string = [NSString stringWithFormat:@"..."]; // i have a real url in place of the ...'s
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    _data = [[operation responseData]dict];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Problem... problem.\n%@", error);
}];

[operation start];

我尝试使用此代码,它不会产生任何错误,但每当我在_data = [[operation responseData]dict];行放置一个断点时,我会发现它是空的。任何帮助,将不胜感激。感谢。

P.S。:这不是重复,所以请不要试图将此问题标记为重复或将此问题投票;我将失去一些特权。

1 个答案:

答案 0 :(得分:1)

试试这个

NSString *string = [NSString stringWithFormat:@"..."]; // i have a real url in place of the ...'s
NSURL *url = [NSURL URLWithString:string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request];
operation.responseSerializer = [AFXMLParserResponseSerializer serializer];
operation.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

if(responseObject)
{
    NSArray *arrData = [response allObjects];
    NSLog(@"Data = %@",arrData);
}
else
{
    NSLog(@"response is empty");
}

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Problem... problem.\n%@", error);
}];

[operation start];

希望这有帮助。