UIView动画被延迟



我正在开发的一个应用程序是拉自定义广告。我检索广告很好,和事情的网络方面工作正常。我遇到的问题是,当AdController接收到一个广告,它解析JSON对象,然后请求图像。

// Request the ad information
NSDictionary* resp = [_server request:coords_dict isJSONObject:NO responseType:JSONResponse];
// If there is a response...
if (resp) {
    // Store the ad id into Instance Variable
    _ad_id = [resp objectForKey:@"ad_id"];
    // Get image data
    NSData* img = [NSData dataWithContentsOfURL:[NSURL URLWithString:[resp objectForKey:@"ad_img_url"]]];
    // Make UIImage
    UIImage* ad = [UIImage imageWithData:img];
    // Send ad to delegate method
    [[self delegate]adController:self returnedAd:ad];
}

所有这些都像预期的那样工作,AdController拉入图像很好…

-(void)adController:(id)controller returnedAd:(UIImage *)ad{
    adImage.image = ad;
    [UIView animateWithDuration:0.2 animations:^{
        adImage.frame = CGRectMake(0, 372, 320, 44);
    }];
    NSLog(@"Returned Ad (delegate)");
}

当委托方法被调用时,它将消息记录到控制台,但是UIImageView* adImage动画需要5-6秒。由于应用程序处理广告请求的方式,动画需要是即时的。

隐藏广告的动画是即时的。

-(void)touchesBegan{
    [UIView animateWithDuration:0.2 animations:^{
        adImage.frame = CGRectMake(0, 417, 320, 44);
    }];
}

如果广告加载发生在后台线程中(最简单的检查方法是[NSThread isMainThread]),那么你不能在同一线程中更新UI状态!大多数UIKit不是线程安全的;当然当前显示的uiview不是。可能发生的事情是主线程没有"注意到"后台线程发生的变化,所以它不会刷新到屏幕,直到其他事情发生。

-(void)someLoadingMethod
{
  ...
  if (resp)
  {
    ...
    [self performSelectorInMainThread:@selector(loadedAd:) withObject:ad waitUntilDone:NO];
  }
}
-(void)loadedAd:(UIImage*)ad
{
  assert([NSThread isMainThread]);
  [[self delegate] adController:self returnedAd:ad];
}

最新更新