我正在尝试使用AFNetworking加载将在应用程序的背景上显示的图像。当viewDidLoad
调用加载图像时,问题就出现了,AFNetworking没有完成加载数据,因此它不显示。
这是我的代码。
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];
任何想法如何做到这一点?
最佳答案
使用您的代码,您将使用AFNetworking下载带有“back_url”的JSON文件,然后在主线程中下载图像,而不是此代码:
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);
}];
关于ios - AFNetworking 2.0和背景图片,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22796052/