Reputation: 31
I'm trying to get weather data by using AFJSONRequestOperation
. The problem is I can't return the object when the query is done. Is there anyone know how to do that?
My current implemation is
- (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];
}
Upvotes: 0
Views: 575
Reputation: 63913
There is a way that you can do this, in a sense. Instead of having a traditional return method you can have the caller pass a block as a parameter, then you can call back to this block inside your success and failure AFJSONRequestOperation
blocks.
Here's an example from some of my code:
- (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);
}
}];
}
}
I call it with this:
[[KSADNAPIClient sharedAPI] postText:postText
forUserName:username
withParameters:parameters
withBlock:^(NSDictionary *response, NSError *error)
{
// Check error and response
}
Upvotes: 0