I'm trying to parse a JSON link using AFNetworking and MJExtensions. see comments in code.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *apiURL = @"https://api.forecast.io/forecast/APIKEY/Lat,Long";
NSURL *URL = [NSURL URLWithString:apiURL];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL.absoluteString parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {
weatherDict = (NSDictionary *)responseObject;
weather = [WeatherClasses mj_objectWithKeyValues:weatherDict];
//----------------------
//when i set the label.text here, the label shows whatever the JSON value is
self.apparentTemperature.text = [NSString stringWithFormat:@"%f", weather.currently.apparentTemperature];
NSLog(@"Temp: %f", weather.currently.apparentTemperature);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
//--------------------------
//but if i set the label here, its always 0 (or nil for NSString)
self.apparentTemperature.text = [NSString stringWithFormat:@"%f", weather.currently.apparentTemperature];
}
while in the success block, my dictionary has data, but when i get out the success block, the dictionary is nil. how can i make it so that the dictionary isn't nil once its set in AFHTTPSessionManager?
using __block didn't work.
//but if i set the label here, its always 0 (or nil for NSString)
That's because that code runs before the network request completes, so the data doesn't exist. When you pass a block into an asynchronous method like a network call, the block will usually execute after the method in which you made the call has exited.
using __block didn't work.
Not surprising. __block
ensures that a variable so marked is used itself inside the block rather than duplicated in the block's context, but it won't make the data come back any faster.
The right solution here is to set your label in the completion block for the request -- that's the sort of thing that completion blocks are for.
how do i keep data once out of block code?
Don't try -- there's no reason not to set the variable inside the block.