这个怎么样,假设weatherContents在类中定义:
weatherAddress = [NSString stringWithFormat:@"http://google.com"];
weatherUrl = [NSURL URLWithString:weatherAddress];
weatherContents = [NSString stringWithContentsOfURL:weatherUrl encoding:NSASCIIStringEncoding error:nil];
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIfWeatherReceived) userInfo:nil repeats:NO];
然后创建一个像这样调用的方法checkIfWeatherReceived
:
-(void) checkIfWeatherReceived
{
if(weatherContents)
{
if ([viewer.request.URL.relativeString isEqualToString:weatherContents]) {
//do stuff
}
} else {
[NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(checkIfWeatherReceived) userInfo:nil repeats:NO];
}
}
我真的不喜欢使用会在您的连接中断时锁定您的界面的东西,所以我会避免只是“让它等待”之类的。如果天气数据已被抓取,这将每半秒检查一次。如果您希望它检查得更快,只需更改 TimeInterval。如果您在数据中没有发现太多延迟,您可能希望它非常快,例如 .01 或其他东西。您还应该考虑如果连接丢失并且您永远无法获取数据会发生什么,除非您已经考虑到这一点。我没有对此进行测试,但我认为它应该可以解决,假设您的所有部分都是类的一部分而不是方法的本地部分。我也可能会将实际工作从checkIfWeatherReceived
另一种方法中分离出来,而不是仅仅将它放在if(weatherContents)
真实区域中。