2014-04-01 51 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