我正在尝试使用 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
中,我有 subview 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/