我正在尝试使用AFJSONRequestOperation
获取天气数据。问题是我在查询完成后无法返回对象。有谁知道怎么做?
我目前的实施是
- (NSDictionary *)getCityWeatherData:(NSString*)city
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://free.worldweatheronline.com/feed/weather.ashx?key=xxxxxxxxxxxxx&num_of_days=3&format=json&q=%@", city]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
NSDictionary *data = [[JSON objectForKey:@"data"] objectForKey:@"weather"];
return data;
} failure:nil];
[operation start];
}
答案 0 :(得分:0)
从某种意义上说,有一种方法可以做到这一点。您可以让调用者将块作为参数传递给您,而不是使用传统的返回方法,然后您可以在成功和失败AFJSONRequestOperation
块内回调此块。
以下是我的一些代码中的示例:
- (void)postText:(NSString *)text
forUserName:(NSString *)username
withParameters:(NSDictionary *)parameters
withBlock:(void(^)(NSDictionary *response, NSError *error))block
{
NSError *keychainError = nil;
NSString *token = [SSKeychain passwordForService:ACCOUNT_SERVICE account:username error:&keychainError];
if (keychainError) {
if (block) {
block([NSDictionary dictionary], keychainError);
}
} else {
NSDictionary *params = @{TEXT_KEY : text, USER_ACCESS_TOKEN: token};
[[KSADNAPIClient sharedAPI] postPath:@"stream/0/posts"
parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
{
if (block) {
block(responseObject, nil);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
if (block) {
block([NSDictionary dictionary], error);
}
}];
}
}
我称之为:
[[KSADNAPIClient sharedAPI] postText:postText
forUserName:username
withParameters:parameters
withBlock:^(NSDictionary *response, NSError *error)
{
// Check error and response
}