您好我从网址获取图片时遇到问题。我从网络服务获取这些网址,然后逐个加载图片,每个网址都附有图片。
-(void)downloadMyfriendReqImage:(NSIndexPath *)path
{
if (path.row<[arrayPendingRequests count]) {
NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"];
UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]];
if (img==nil) {
img=[UIImage imageNamed:@"placeholder.png"];
}
[dicPendingReqImages setObject:img forKey:str];
[tblFriendRequests performSelectorOnMainThread:@selector(reloadData) withObject:@"TAG_29" waitUntilDone:NO];
}
}
这是我用来加载图片的方式。但问题是有些图像没有得到。 img
变为空值。但我在android中有相同的应用程序。它完美地加载了所有这些图像。有什么问题..任何人都可以帮助我。
答案 0 :(得分:0)
在将NSData请求转换为图像之前检查NSData请求的结果。可能是你从服务器收到超时。
答案 1 :(得分:0)
-(void)downloadMyfriendReqImage:(NSIndexPath *)path
{
if (path.row<[arrayPendingRequests count]) {
NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"];
//ADDED LINE
str=[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:str]]];
if (img==nil) {
img=[UIImage imageNamed:@"placeholder.png"];
}
[dicPendingReqImages setObject:img forKey:str];
[tblFriendRequests performSelectorOnMainThread:@selector(reloadData) withObject:@"TAG_29" waitUntilDone:NO];
}
}
我认为你的网址包含一些像NSURL
无法读取的空格这样的字符,为了使它能够为字符串添加编码,我认为它应该以这种方式工作..检查代码{{1 }}
答案 2 :(得分:0)
试试这个:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *str=[[arrayPendingRequests objectAtIndex:path.row]valueForKey:@"USERIMAGE"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:str]];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error) {
// handle error
return;
}
dispatch_async(dispatch_get_main_queue(), ^{
// do something with the data
UIImage *img = [[UIImage alloc] initWithData:data];
});
});