2014-04-01 55 views
1

我试图加载将在我的应用程序的背景通过使用AFNetworking要显示的图像。问题是当该viewDidLoad调用加载图像时,AFNetworking尚未完成加载数据,因此它不会显示。AFNetworking 2.0&背景图像

这里我的代码。

AFNetworking

AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
operation.responseSerializer = [AFJSONResponseSerializer serializer]; 

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 

    // 3 
    NSDictionary *user = (NSDictionary *)responseObject; 

    NSString *backurlJSON=[user valueForKeyPath:@"back_url"][0]; 
    NSLog(@"Background from Start: %@",backurlJSON); 

    if(![backurlJSON isEqualToString:@""]){ 

     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mydomain.com/images/%@", backurlJSON]]; 
     NSData *data = [[NSData alloc]initWithContentsOfURL:url ]; 
     imgBack = [[UIImage alloc]initWithData:data ]; 

     backgroundView = [[UIImageView alloc] initWithImage: imgBack]; 

所以在viewDidLoad我有子视图UIImageView加载图像,如果没有图像加载,我会喜欢从一来覆盖AFNetworking

viewDidLoad中

background = [UIImage imageNamed: @"2.png"]; 
backgroundView = [[UIImageView alloc] initWithImage: background]; 
backgroundView.frame = CGRectMake(-10, -10, 340, 588); 
backgroundView.contentMode = UIViewContentModeScaleAspectFill; 
[self.view addSubview:backgroundView]; 

任何想法如何做到这一点?

回答

1

与您的代码,您正在使用AFNetworking下载一个JSON文件与“back_url” ,那么你下载的图像在主线程,而不是此代码:

if(![backurlJSON isEqualToString:@""]){ 

    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mydomain.com/images/%@", backurlJSON]]; 
    NSData *data = [[NSData alloc]initWithContentsOfURL:url ]; 
    imgBack = [[UIImage alloc]initWithData:data ]; 

    backgroundView = [[UIImageView alloc] initWithImage: imgBack]; 
} 

您可以使用类似:

NSString *backurlJSON=[user valueForKeyPath:@"back_url"][0]; 
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.mydomain.com/images/%@", backurlJSON]]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 


    AFHTTPRequestOperation *postOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 
    postOperation.responseSerializer = [AFImageResponseSerializer serializer]; 
    [postOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
     backgroundView.image = responseObject; 

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
     NSLog(@"Image error: %@", error); 
    }]; 
+1

这项工作完美,谢谢! –

1

它看起来像你覆盖你的UIImageView,绝不添加回视图层次结构。试着改变你的形象视角的图像属性,而不是创建一个新问题:

[backgroundView performSelectorOnMainThread:@selector(setImage:) withObject:imgBack waitUntilDone:NO]; 

,而不是

backgroundView = [[UIImageView alloc] initWithImage: imgBack]; 
+0

我个人比较喜欢'dispatch_async(dispatch_get_main_queue(),^ {/ * do stuff on main thread * /});'执行'performSelectorOnMainThread:withObject:waitUntilDone:'。没有什么内在的错误你的方式(这是/是常态),但它仅在情况下,你只需要一个操作执行的工作,需要为它不超过一个参数。 – aapierce