Problems with UIImagePNGRepresentation - uiimage

I'm trying to use this line of code
[UIImagePNGRepresentation(image, 1.0) writeToFile:pngPath atomically:YES];
But obviously pngPath is undeclared. So I have to use stringByAppendingPathComponent.
I googled examples of this, and I found this
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName] ];
[myPlistPath retain]
;
The problem is that I don't have a plist file, because I don't need one. How can I solve all these issues and writeToFile the UIImage image?

I don't fully understand your question, but to get the full path where your file should be saved, you could try this:
NSString *file = #"myfile.png";
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [directory stringByAppendingPathComponent: file];
and then:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

Related

How do I read from /Library/Application Support/ folder?

I am making a OX Cocoa app and I want to be able to read and write text files using the app on button press. These text files should be saved in /Library/Application Support/AppName but i can't get my app to reading anything from there. It can write to the folder, but not read what it has written there, even though I can see the file sitting there in finder.
Here is the code I am using the successfully write to the folder.
NSString *text = editor.string;
NSString *path = #"/Library/Application Support/";
NSMutableString *mu = [[NSMutableString stringWithString:path] init];
[mu insertString:FileName.stringValue atIndex:mu.length];
[mu insertString:#".txt" atIndex:mu.length];
path = [mu copy];
[text writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL];
Here is the code I am using (and failing) to read from the text files.
NSArray *path = [[NSBundle mainBundle] pathsForResourcesOfType:#"txt" inDirectory:#"/Library/Application Support/"];
NSString *output = #"";
NSMutableString *mu = [[NSMutableString stringWithString:output] init];
for (int i = 0; i < [path count]; i++) {
NSString *text = [NSString stringWithContentsOfFile:path[i] encoding:NSUTF8StringEncoding error:NULL];
[mu insertString:text atIndex:mu.length];
[mu insertString:#"\n" atIndex:mu.length];
}
[textView setString:mu];
Any tips on what I can correct would be super helpful, I'm a bit stuck here.
Edit: Using your input I have updated my code to this:
NSString *fileLocation = #"~/Library/Application Support/";
NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:nil];
NSString *output = #"";
NSMutableString *mu = [[NSMutableString stringWithString:output] init];
for (int i = 0; i < [text count]; i++) {
[mu insertString:text[i] atIndex:mu.length];
[mu insertString:#"\n" atIndex:mu.length];
}
[textView setString:mu];
However the text from the files is still not appearing.
Most hard-coded paths will fail when you sandbox your app. Even if you get away with this one, or you don't plan to sandbox this app, it's a bad habit that's worth getting out of.
Moreover, are you sure you want /Library and not ~/Library? The former is often not writable by the user. The latter is in the user's Home directory (or your container when sandboxed).
To get the Application Support directory, or the Caches directory, or any other directory that you may want to create things in and later retrieve them from, ask a file manager for it.
/Library/Application Support is not in your bundle. The paths you get using [[NSBundle mainBundle] pathsForResourcesOfType:…] are only useful for accessing files inside your application itself (images, sounds, etc that you included when you built the app).
You want to use [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:error] to get a list of files in a directory outside your application.
Matt Gallagher has a great example of a fault-tolerant method of locating the path to your application support directory at Cocoa With Love. I would recommend using it over hardcoding the /Library/Application Support path.
NSError *error = nil;
NSArray *text = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:fileLocation error:&error];
if (!text) {
NSLog( #"Error reading contents of application support folder at %#.\n%#", applicationSupportFolder, [error userInfo] );
}
You're trying to get the path using NSBundle from the main bundle of the app. But the file is not in the bundle, you should specify the path manually. You could hardcode the path, store previously written paths somewhere, or use NSFileManager to get directory contents and analyze it. For example, -[NSFileManager contentsOfDirectoryAtPath:error:].

What’s the correct way to create an NSURL from an NSString?

I’ve got an NSString that stores the path to a saved file:
NSString *filePath = [NSString stringWithFormat:
#"%#/someFolder/%#",
NSHomeDirectory(),
[NSString stringWithFormat:#"%#",[self.fileName stringByAppendingPathExtension:#"txt"]]];
And it’s OK — when I log it, I get:
/Users/username/someFolder/fileName.txt
So my next step is to make an NSURL object from this NSString. I did this:
NSURL *pathURL = [NSURL URLWithString:[NSString stringWithFormat:#"%#", filePath]];
NSLog(#"URL = %#", pathURL);
but the response is:
URL = (null)
What’s wrong here? How can I do this correctly?
A path is not a valid URL by itself. You have to use this:
NSURL *pathURL = [NSURL fileURLWithPath:filePath];
And read the documentation. (And don’t overuse / abuse format strings.)

How to get the path/directory component from a NSURL?

I retrieved a NSURL from a NSSavePanel. I now have this NSURL which gives me the following:
file://localhost/Users/brett/Documents/asdf%20asdf.json
Now, it is easy for me to retrieve just the filename using something like the following:
[[[NSFileManager defaultManager] displayNameAtPath:pathAndFilename] stringByDeletingPathExtension]
This gives me just the localized filename, as expected: asdf%20asdf
So, how do I get the path, like so: file://localhost/Users/brett/Documents/
-[NSURL URLByDeletingLastPathComponent] is the simplest way to achieve this.
You could use NSString methods to work with file paths. For example,
NSString *directory = [[URL absoluteString] stringByDeletingLastPathComponent];
NSString *filename = [[URL absoluteString] lastPathComponent];
You could find other useful methods in Apple Docs: NSString Class Reference -> Working with Paths section
Directly from your NSSavePanel:
NSSavePanel *savePanel;
...
NSString *path = savePanel.directoryURL.path;

Reading desktop plist

I am using following code to read the details of the plist,
NSString *plistPath = #"~/Library/Preferences/com.apple.desktop.plist";
NSDictionary *plistData = [NSDictionary dictionaryWithContentsOfFile:plistPath];
But plistData has no entries.
Is there something wrong in above code?
You need expanding the tilde. Try this:
NSString * plistPath = [#"~/Library/Preferences/com.apple.desktop.plist" stringByExpandingTildeInPath];

Use stringWithFormat: as a file path in cocoa

I'm having a problem with a cocoa application that takes the value of a text field, and writes it to a file. The file path is made using stringWithFormat: to combine 2 strings. For some reason it will not create the file and the console says nothing. Here is my code:
//Get the values of the text field
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
//Use stringWithFormat: to create the file path
NSString *filePath = [NSString stringWithFormat:#"~/Library/Application Support/Test/%#.txt", fileName];
//Write the username to filePath
[username writeToFile:filePath atomically:YES];
Thanks for any help
The problem is that you have a tilde ~ in the path. ~ is expanded by the shell to the user's home directory, but this doesn't happen automatically in Cocoa. You want to use -[NSString stringByExpandingTildeInPath]. This should work:
NSString *fileName = [fileNameTextField stringValue];
NSString *username = [usernameTextField stringValue];
NSString *fileName = [fileName stringByAppendingPathExtension:#"txt"]; // Append ".txt" to filename
NSString *filePath = [[#"~/Library/Application Support/Test/" stringByExpandingTildeInPath] stringByAppendingPathComponent:fileName]; // Expand '~' to user's home directory, and then append filename
[username writeToFile:filePath atomically:YES];
Adding to mipadi's reply, it's better to use -[NSString stringByStandardizingPath] since it does more - and can clean up more problems - than resolving the tilde.

Resources