简体   繁体   中英

Why won't this image show up? Using NSData and initWithData

NSURL* urlEx = [NSURL URLWithString:@"Pacific_Map.png"];
NSData* mapExIMGData = [[NSData alloc] initWithContentsOfURL: urlEx];

UIImage* imgEx = [[UIImage alloc] initWithData:mapExIMGData];

mapImageViewEx.image = imgEx;

If I replace mapImageViewEx.image = imgEx; with mapImageViewEx.image = [UIImage imageNamed:@"Pacific_Map.png"]; it works, but I do not want to use imageNamed.

That's because imageNamed knows where to scan for the file, but initWithContentsOfURL expects the full path. use

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"Pacific_Map" ofType:@"png"];
NSURL* urlEx = [NSURL fileURLWithPath:imagePath];
NSData* mapExIMGData = [[NSData alloc] initWithContentsOfURL: urlEx];

UIImage* imgEx = [[UIImage alloc] initWithData:mapExIMGData];

mapImageViewEx.image = imgEx;

What's wrong with using imageNamed? Anyway, you could use initWithContentsofPath.

+ (UIImage *)imageWithContentsOfFile:(NSString *)path

Tell us more about what you are trying to accomplish. Good luck,

James

EDIT: Sorry, I assumed Pacific_Map.png was just a placeholder path. Like someone else posted, you need to indicate the full path if you're not going to use imageNamed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM