NSData *imgData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:post.imageURL]];
UIImage *img = [[UIImage alloc] initWithData:imgData];
我有这个代码,imgData总是没有。我检查了post.imageURL,它返回一个url格式的字符串。我还用一个我硬编码的常量字符串(URL格式)替换了字符串,但imgData仍然为null。此代码在后台运行。你们看到有什么问题吗?
答案 0 :(得分:1)
您的代码看起来不错,您确定您的网址有效吗? 如果post.imageURL无效,那么URLWithString:将为null,也是您的数据。
我已尝试使用“http://www.google.com/intl/en_ALL/images/srpr/logo1w.png”来确定,并且它有效,所以我猜问题来自您的网址。
拆分代码:
NSURL *url = [NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/srpr/logo1w.png"];
NSData *imgData = [[NSData alloc] initWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:imgData];
并检查每个变量的值。