UIImage with NSData initWithData is nil - ios

The following code does not seem to load an image.
uiTabBarItem = [[UITabBarItem alloc] init];
NSData *datatmp = [NSData dataWithContentsOfFile:#"newsicon.png"];
UIImage *tmp = [[UIImage alloc] initWithData:datatmp];
uiTabBarItem.image = tmp;
datatmp is nil (0x000000) and
the image does exist.

I. Don't reinwent the wheel. Use tmp = [UIImage imageNamed:#"newsicon.png"]; instead.
II. NSData expects a full file path when being initialized from a file. The following would work (but you don't have to use this anyway, as I just pointed it out):
NSString *iconPath = [[NSBundle mainBundle] pathForResource:#"newsicon" ofType:#"png"];
NSData *datatmp = [NSData dataWithContentsOfFile:iconPath];

Loading an image from a file is best accomplished with:
[UIImage imageNamed: "newsicon.png"];

Related

Why is NSFileManager unable to find these png files?

I have written code to open image files after studying answers to the questions found here (a, b, c, d, e, f & g). But NSFileManager is unable to find them even though I added the png files to the project. I'm reasonably confident my code should be able to recognise either of the png files if they were in the right directory.
e.g.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
NSLog(#"\ndirPaths %# \n\ndocsDir \n%#", dirPaths, docsDir);
NSString *imageFilePath = [docsDir stringByAppendingPathComponent:#"iTunesArtwork1024.png"];
NSLog(#"\n\nfile path should be \n\n%# \n\n", imageFilePath);
NSData *imageData = [NSData dataWithContentsOfFile:imageFilePath];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageWithData:imageData];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
[self.view addSubview:logo];
}
But here is the log in the debug window
2017-07-14 18:26:35.679 IconShape[1089:348564]
dirPaths (
"/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents"
)
docsDir
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents
2017-07-14 18:26:35.679 IconShape[1089:348564]
file path should be
/Users/gs/Library/Developer/CoreSimulator/Devices/57279C80-0937-4658-B0E6-7984B3768D56/data/Containers/Data/Application/18235DBF-7ADB-47D4-AFF9-282D02F2A0F8/Documents/iTunesArtwork1024.png
2017-07-14 18:26:35.679 IconShape[1089:348564]
Image file not found
Here is the state of the project after two png files were added.
Yet the log shows they are not visible to NSFileManager. So where would they be found ? i.e. what changes do I need to make to my code in order to find them ?
EDIT
This draft finds the png file following Subramanian's recommendation.
- (void)viewDidLoad {
[super viewDidLoad];
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSString *imageFilePath = [[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];
if ([fileManager fileExistsAtPath:imageFilePath])
{
NSLog(#"\nFound file path : %#", imageFilePath);
}
else
{
NSLog(#"\nImage file not found");
}
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 50, 50)];
logo.image = image;
[self.view addSubview:logo];
}
The log now reads
Found file path : … .app/iTunesArtwork1024.png
and the image also appears in the subview.
__
Image is not in theDocument Directory, It's inside the bundle.
You have added the image files inside the project. But You are checking the image on Document Directory, Which is wrong. Image is inside app bundle.
You can simply assign the Image to UIImageView by the name of the image.
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
UIImageView *logo = [[UIImageView alloc] init];
logo.image = image;
If you want to get the path of the image, then you have to use [NSBundle mainBundle]
[[NSBundle mainBundle]pathForResource:#"iTunesArtwork1024" ofType:#"png"];
You can access images with names which are added in projects. Try with below code
UIImage *image = [UIImage imageNamed:#"iTunesArtwork1024.png"];
The path where your are looking for the image is inside your device (real or simulator).
To load an image that is stored in your XCode project just do:
UIImage* image = [UIImage imageNamed:#"iTunesArtwork1024.png"];

iOS Objective-C Display PNG Image In Custom Framework

I'm creating a custom framework. Previously in the framework we would download an image and use that to display in a button:
NSString *path = [NSString stringWithFormat: #"https://s3.amazonaws.com/assets/home.png"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *homeButton = [[UIImage alloc] initWithData:data];
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButton imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: #selector(backToRewardsCenter:)];
However, in reviewing this we determined that this isn't good to have as a synchronous call so I'd like to add this PNG to the framework itself.
I've been able to do this by adding the image and ensuring it's included in the copy bundle resources Build Phase. With this set the image gets added in the universal framework output:
However, when I attempt to add this in code, it doesn't seem to show up. Also, when I add the framework in a project, I don't see the image being included, just the headers:
Here's what I've tried so far:
NSString* path = [NSString stringWithFormat:#"%#/TheoremReachSDK.framework/home.png", [[NSBundle mainBundle] bundlePath]];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
And:
NSBundle *bundle = [NSBundle bundleForClass:[TheoremReach class]];
NSString *path = [bundle pathForResource:#"home" ofType:#"png"];
UIImage *homeButton = [[UIImage alloc] initWithContentsOfFile:path];
And:
UIImage *homeButton = [UIImage imageNamed:#"home.png"];
But none of those display anything. Any idea what I need to do to get the image to display?
I'm guessing NSBundle isn't finding the framework via the call to:
[NSBundle bundleForClass:[TheoremReach class]]
Try giving your framework an explicit bundle ID, e.g.: com.theoremreach.sdk, clean your projects and then rebuild.
You can then use code like this to fetch and display your image:
NSString *bundleIdentifier = #"com.theoremreach.sdk";
NSBundle *bundle = [NSBundle bundleWithIdentifier:bundleIdentifier];
if(bundle != nil) {
NSString *path = [bundle pathForResource:#"home" ofType:#"png"];
UIImage *homeButtonImage = [[UIImage alloc] initWithContentsOfFile:path];
if(homeButtonImage != nil) {
self.rewardsCenterButton = [[UIBarButtonItem alloc] initWithImage:[homeButtonImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]
style:UIBarButtonItemStylePlain
target:self
action: #selector(backToRewardsCenter:)];
} else {
NSLog(#"couldn't find home button image in bundle");
}
} else {
NSLog(#"could not find bundle with identifier %#", bundleIdentifier);
}

UIImage Object Not Formed Using NSData

I am getting the following response from a server:
{
"userId": "72e823ebc0c07fa99f279d6435e2c6ce",
"userHash": null,
"md5": "e993b7e9ec74bcdc1b1b7baec7d1cdd2",
"highres": null,
"thumbnail": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0
Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/
8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2Jygg
kKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytL
T1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJ
BUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZa
XmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0CfRbZY3IzuAyOak0nTLOW0UzBt+e
cGpppcxvg87ajt76Cw0R7uVC3lgtj1rREMvtpVijo6q+5fu81Wu/EGmeFFMlwTiTkgHmnadqqanYwXqL5ayDIU9q8C8ceILq+8QXUU0haOFyqgelVo9xHu1v8U9BuLhIlM
g3fxHGBXWf2pYmAzLdRMgXdw4NfImmQXN1bNIHKQbsbj616DpdvcQ6RHsnLfNyc1jNpbGqi+p6+fHOmgkbJePaivMvN9jRWPOyuU6Rb9ZbaTyn3Ng4Feaaj48utIuNQ0
+6gaaOZNiKT/q/etvSPEEN1qr2dsoMAXcJMdTXJ61aaLe+K7v+2b1rSIAbSozmutbmD2Lnhzxvq2h26me1e6tZB+7JPCCuauBHqGvTXV04hjuHL4Pato+CdcvlWTSZGn0w/
wCpdmxkV01v8IIZbWOa51NhPtyybhhT6U7Kw07M56xvbGK3NpFGrpuyYx39627PXoJrmSwtYgFij35Hc+ldX4L8IDStMvoryxtpk2vtuHYbhxxXiVrcTaZ4gujAxk3uynJ6DN
YOkbqonY7I+KLgEj+zz+dFZWQeTIaKz9ia3j3I9F1+8e2ElrDArg5cnj5awdfli1PUJbqR/vDtWTBev9i+zKSOc5FUHDocFifxrpujiOoj8b6vDpkelQymOCIbUKNg4qEajrcoBW/
uMe8hrnIpPLmRm6A1urq8JRRtORTTBov2q+JtRlFtb6jcDdxgykA1txfC3xRBKks3kruIO5nxmsrRdVd7sKgwi/MD7ivZ/C+taV490waVq8rRX0XKurbQQOlS2UkcaPh5reB+
9tf+/gor0j/hVqZ4upsf9dDRSuOx8q2v3z9KJetFFBmyCTotSRfdNFFNF9Do/DvR/oa2vCrMPEdphiP346H3oopD6H1un+rX6CiiipGf/9k="
}
Thumbnail is a byte array and I want to convert that into NSData, then into an UIImage.
When I do the following, I end up with nil:
NSData *pictureData = [NSData dataWithBytes:[updatedData objectForKey:#"thumbnail"]];
UIImage *img = [[UIImage alloc] initWithData:pictureData];
How can I fix this?
This is not a "byte array". This is a NSString which contains a Base64 encoded image.
iOS7 has built in support for Base64 encoded data, for older versions you have to roll your own code. There are plenty of implementations available
This works on iOS7:
// NSString *base64String = [updatedData objectForKey:#"thumbnail"];
NSString *base64String = #"/9j/4AAQSkZJRgABAgAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCAAyADIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD0CfRbZY3IzuAyOak0nTLOW0UzBt+ecGpppcxvg87ajt76Cw0R7uVC3lgtj1rREMvtpVijo6q+5fu81Wu/EGmeFFMlwTiTkgHmnadqqanYwXqL5ayDIU9q8C8ceILq+8QXUU0haOFyqgelVo9xHu1v8U9BuLhIlMg3fxHGBXWf2pYmAzLdRMgXdw4NfImmQXN1bNIHKQbsbj616DpdvcQ6RHsnLfNyc1jNpbGqi+p6+fHOmgkbJePaivMvN9jRWPOyuU6Rb9ZbaTyn3Ng4Feaaj48utIuNQ0+6gaaOZNiKT/q/etvSPEEN1qr2dsoMAXcJMdTXJ61aaLe+K7v+2b1rSIAbSozmutbmD2Lnhzxvq2h26me1e6tZB+7JPCCuauBHqGvTXV04hjuHL4Pato+CdcvlWTSZGn0w/wCpdmxkV01v8IIZbWOa51NhPtyybhhT6U7Kw07M56xvbGK3NpFGrpuyYx39627PXoJrmSwtYgFij35Hc+ldX4L8IDStMvoryxtpk2vtuHYbhxxXiVrcTaZ4gujAxk3uynJ6DNYOkbqonY7I+KLgEj+zz+dFZWQeTIaKz9ia3j3I9F1+8e2ElrDArg5cnj5awdfli1PUJbqR/vDtWTBev9i+zKSOc5FUHDocFifxrpujiOoj8b6vDpkelQymOCIbUKNg4qEajrcoBW/uMe8hrnIpPLmRm6A1urq8JRRtORTTBov2q+JtRlFtb6jcDdxgykA1txfC3xRBKks3kruIO5nxmsrRdVd7sKgwi/MD7ivZ/C+taV490waVq8rRX0XKurbQQOlS2UkcaPh5reB+9tf+/gor0j/hVqZ4upsf9dDRSuOx8q2v3z9KJetFFBmyCTotSRfdNFFNF9Do/DvR/oa2vCrMPEdphiP346H3oopD6H1un+rX6CiiipGf/9k=";
NSData *data = [[NSData alloc] initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
UIImage *image = [UIImage imageWithData:data];
And that's your image:

How to display an UIImage in a custom cell

I am trying to display an Logo image in my custom cell, from amazon Amazon S3 bucket though StackMob
but its not showing. if l paste the direct url path to the image it works, how do i get around this.
NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
CGRect imageFrame = CGRectMake(2, 2, 67, 67);
self.customImage = [[UIImageView alloc] initWithFrame:imageFrame];
NSURL* imageURL = [NSURL URLWithString:[object valueForKey:#"restoLogo"]];
NSData *data = [[NSData alloc] initWithContentsOfURL:imageURL];
UIImage *tmpImage = [[UIImage alloc] initWithData:data];
self.customImage.image = tmpImage;
[cell.contentView addSubview:self.customImage];
the image is at this path [object valueForKey:#"restoLogo"] now returns the s3 url for the data.
If you are not using NSString's instance method
stringByAddingPercentEscapesUsingEncoding:
that could be the issue.
For example
NSString *escapedString = [imgURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Then turn it into a URL and continue on your way.

UIImage is empty after calling imageWithContentsOfFile

As you can see, that I have put my the national flags in a folder in Xcode and I am trying to display it to the navigation bar. However, it is not showing up and I found out:
NSString *imageName = [NSString stringWithFormat:#"%#.icns",countryName];
UIImage *image = [UIImage imageWithContentsOfFile:imageName];
image is "nil".
Any idea? Thanks!
You could use like this
NSString *imageName = [NSString stringWithFormat:#"%#.icns",countryName];
UIImage *image = [UIImage imageNamed:imageName];
Please Try This
Check whether the file actually exists. I suspect it doesn't. Use [NSFileManager defaultManager] fileExistsAtPath:.
Where was the image path you are sending NSString to here
UIImage imageWithContentsOfFile:imageName
send the path to that method. or make like this
UIImage *image = [UIImage imageNamed:[NSString stringwithFormat:#"%#.icns",countryName]];

Resources