Get file type description by extension - objective-c

How can I get the description of the file type like it does in Finder.app by using only file extension? In other words I want to get that field in NSString:

Here's a little something quick 'n' dirty that illustrates what you need:
NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
[openPanel runModal];
NSString *path = [[openPanel URL] path];
NSString *type = [[NSWorkspace sharedWorkspace] typeOfFile:path error:NULL];
NSLog(#"%#", [[NSWorkspace sharedWorkspace] localizedDescriptionForType:type]);
The open panel lets you choose a file. NSWorkspace provides for first determining the UTI of the file (given its path), and then using the UTI to get the localized string describing the file type.
EDIT:
If you positively have got to use only the file extension, then use these three lines instead of the last three above:
NSString *extension = [[[openPanel URL] path] pathExtension];
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef) extension, NULL);
NSLog(#"%#", [[NSWorkspace sharedWorkspace] localizedDescriptionForType:(__bridge NSString *) uti]);

You should get that by supplying the files universal type identifier to localizedDescriptionForType: of NSWorkspace.

Related

how to write to a file if I have path xcode

I'm trying to make a plugin for xcode where I want to write something to the h file from the m file. I can dynamically get the filepath from the class I'm currently writing code in, and by changing the .m to .h I'll have the filepath for the h file.
My question is, how do I write something to an .h file from xcode when I have the path?
NSString *path = #"your/path/tp/.h/file";
NSData *data = [NSData dataWithContentsOfFile:path];
//Get the contents of the file into the mutable string
NSMutableString *contents = [[NSMutableString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
//Make changes to your mutable string
[contents appendString:#"abc"];
//Write it back to the file
[contents writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil];
It´s not possible to do what you are asking. You can write only in files from your Documents Directory.
I don´t understand why do you need to write in a .h file for to change it. Maybe you could create subclasses from the same Class and you use one or other depending of your requirements

Use NSOpenpanel and NSfilemanager to find contents of directory

I'm new to objective-c so please excuse my lack of knowledge. I have a snippet of code here that I can't seem to get working properly. What I'd like to do is present a directory selection panel upon a button click. Once the user selects a directory I'd like to make an array of everything in the directory. Eventually I want to use this array to have a list of sub-directories and files (everything in the directory the user selects) to be copied to another location.
I have a warning that says Instance method '-contentsofdirectoryaturl:options:error' not found (return type defaults to id). I'm not exactly sure what that means or how to fix it and I suspect that this is my problem. Any advice provided would be great. Thanks!
- (IBAction)selectfiles:(id)sender {
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseDirectories:YES];
[openPanel setCanChooseFiles:NO];
[openPanel setAllowsMultipleSelection:NO];
if ( [openPanel runModal] == NSOKButton ) {
NSArray *accountPath = [openPanel URLs];
NSLog (#"%#", accountPath);
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *contents;
contents = [filemgr contentsOfDirectoryAtURL:accountPath options:(NSDirectoryEnumerationSkipsHiddenFiles) error:nil];
}
}
contentsOfDirectoryAtURL: has an additional argument includingPropertiesForKeys: which you have omitted. That is why the compiler warns you. That argument is a list of properties you want to be prefetched. In the simplest case, you can specify an empty array.
Another error is that [openPanel URLs] returns an array of URLs, even if only one item is selected.
So your code should look like this:
NSURL *accountPath = [[openPanel URLs] objectAtIndex:0];
NSLog (#"%#", accountPath);
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *contents;
contents = [filemgr contentsOfDirectoryAtURL:accountPath
includingPropertiesForKeys:[NSArray array]
options:(NSDirectoryEnumerationSkipsHiddenFiles)
error:nil];

Parsing of m3u files in Objective-C for iPhone from file system or URL

The example below should take a link from m3u playlist and add it to anArray. (So I will get the NSArray(NSMutableArray) with certain links in it)
NSString *fileContents = [NSString stringWithContentsOfFile:#"myfile.m3u" encoding:NSUTF8StringEncoding error:NULL];
NSArray *lines = [fileContents componentsSeparatedByString:#"\n"];
NSLog (#"%#",lines);
All the time I had (null) in NSLog Message.
All the time when I try NSLog or if/else statement to check is there is link in array it gives me the null object in it.
After that I thought the problem was in m3u type and I've tried to change type in txt and read. (For those who don't know, M3U is just the text in UTF-8 encoding and the changing type should give the result)
Then I've tried the .txt files but it doesn't work too. So there is the code of it.
//Check if there is my file
NSString *addPath = [[NSBundle mainBundle] pathForResource:#"somefile" ofType:#"m3u" ];
if ([fileMgr fileExistsAtPath:addPath] ) {
NSLog(#"Yes.We see the file");
}
else {
NSLog(#"Nope there is no file");
}
//Rename
NSString *path1 = addPath;
NSString *theNewFilename = [path1 stringByReplacingOccurrencesOfString:#"m3u" withString:#"txt"];
NSLog(#"Renamed file adress is %#", theNewFilename);
//Check if there is our renamed file(file manager was allocated before)
NSString *addPath1 = [[NSBundle mainBundle] pathForResource:#"somefile" ofType:#"txt" ];
if ([fileMgr fileExistsAtPath:addPath1] ) {
NSLog(#"Yes we had the renamed file");
}
else {
NSLog(#"No we don't");
}
Checking is there is m3u file worked fine. I had Addres to Renamed file too. But when it was checking is there is renamed file, there was no file (null in NSLog).
After all that stuff, and without any hope to reach my destination I've tried to read txt file line by line separated by /n with 5 links in it.
NSString *fileContents1 = [NSString stringWithContentsOfFile:#"myfile.txt" encoding:NSUTF8StringEncoding error:NULL];
NSArray *lines1 = [fileContents1 componentsSeparatedByString:#"\n"];
NSLog (#"%#",fileContents1);
NSLog (#"%#",lines1);
Both Messages were NULL
One more thing all this stuff I tried to make in -(IBAction)fileRead { } linked to button
(Yes I've presed button every time to check my NSLog)Program was checked in iPhone Simulator. Will be glad if someone say what is the trouble. Also if there is easier way to make this with url. (Tried Couple times with NSUrl and had Nothing but null )
Just because you've changed the path doesn't mean that you've renamed/moved/copied an item, path is just a string. Use NSFileManager methods like
– moveItemAtURL:toURL:error: or
– moveItemAtPath:toPath:error:.
Also, NSString doesn't care about extension, so it's completely safe to read your m3u file to NSString, no need to rename it.
NSString *addPath = [[NSBundle mainBundle] pathForResource:#"somefile" ofType:#"m3u" ];
if ([fileMgr fileExistsAtPath:addPath] ) {
NSLog(#"Yes.We see the file");
NSString *fileContents1 = [NSString stringWithContentsOfFile:addPath encoding:NSUTF8StringEncoding error:NULL];
NSArray *lines1 = [fileContents1 componentsSeparatedByString:#"\n"];
NSLog (#"%#",fileContents1);
NSLog (#"%#",lines1);
}
else {
NSLog(#"Nope there is no file");
}

Problem getting files from folder, error recognizing folder. (Objective c)

I have the user select a folder from an NSOpenPanel. This returns a filepath like: file://localhost/Folder. Here is my code where it all goes wrong:
NSURL *filePath = [openDlg URL]; //OpenDlg is my NSOpenPanel
NSString *s = [filePath absoluteString];
NSLog(#"%#",s);
NSError *error;
NSArray *b = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:s error:&error];
if (error) {
NSLog(#"%#",error);
}
NSLog(#"%lu",b.count);
Here, no matter what folder I select, this error message is sent: The folder “Folder” doesn’t exist." UserInfo=0x10518b320 {NSFilePath=file://localhost/Folder, NSUserStringVariant=(
Folder
), NSUnderlyingError=0x10515d5e0 "The operation couldn’t be completed. (OSStatus error -43.)"}
What is going on?!? If this isn't the best way to do it how can I access all the files inside of a folder?
Try using this method instead:
- (NSArray *)contentsOfDirectoryAtURL:(NSURL *)url includingPropertiesForKeys:(NSArray *)keys options:(NSDirectoryEnumerationOptions)mask error:(NSError **)error
You can just pass in the NSURL without having to convert it into a NSString. To give you an example of how you would use it, see below:
[[NSFileManager defaultManager] contentsOfDirectoryAtURL:filePathURL
includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, nil]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:&error];
I can't see how you setup your NSOpenPanel so I will also include an example of how to set that up below:
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSArray* urls = [openPanel URLs];
NSURL *url = [urls objectAtIndex:0];
if (url != nil) {
// If you want to convert the path to a NSString
self.filePathString = [url path];
// If you want to keep the path as a NSURL
self.filePathURL = url;
}
}
}];
The above method will get the path to the file or folder after the user has pressed the OK button. Give that a try and see if it works. To further elaborate on why I suggested you use NSURL, here is the explanation that the Apple Documentation gives:
The preferred way to specify the location of a file or directory is to use the NSURL class. Although the NSString class has many methods related to path creation, URLs offer a more robust way to locate files and directories. For applications that also work with network resources, URLs also mean that you can use one type of object to manage items located on a local file system or on a network server.

How to Find & Replace text in a file using Objective C?

I am new to Xcode and was wondering if anyone could help me with this.
I need to make an application that is able to open a file and replace its contents.
E.g. (in psuedo code)
Replace("String1", "String2", "~/Desktop/Sample.txt")
Please let me know if I'm not clear enough.
Thanks in advance.
use stringByReplacingOccurrencesOfString:withString: method which will find all occurrences of one NSString and replace them, returning a new autoreleased NSString.
NSString *source = #"The rain in Spain";
NSString *copy = [source stringByReplacingOccurrencesOfString:#"ain"
withString:#"oof"];
NSLog(#"copy = %#", copy);
// prints "copy = The roof in Spoof"
Edit
to set the file content in your string (be careful , this is not conveniant if your file is a bit large) , replace occurences then copy to a new file :
// Instantiate an NSString which describes the filesystem location of
// the file we will be reading.
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:#"Sample.txt"];
NSError *anError;
NSString *aString = [NSString stringWithContentsOfFile:filePath
encoding:NSUTF8StringEncoding
error:&anError];
// If the file read was unsuccessful, display the error description.
// Otherwise, copy the string to your file.
if (!aString) {
NSLog(#"%#", [anError localizedDescription]);
} else {
//replace string1 occurences by string2
NSString *replacedString = [aString stringByReplacingOccurrencesOfString:#"String1"
withString:#"String2"];
//copy replacedString to sample.txt
NSString * stringFilepath = #"ReplacedSample.txt";
[replacedString writeToFile:stringFilepath atomically:YES encoding:NSWindowsCP1250StringEncoding error:error];
}
You probably want this
And regarding your question about how to read the text from a file to a NSString:
NSError * error;
NSString * stringFromFile;
NSString * stringFilepath = #"loadfile.txt";
stringFromFile = [[NSString alloc] initWithContentsOfFile:stringFilepath
encoding:NSWindowsCP1250StringEncoding
error:&error];
And for writing to a file:
(using the same NSString from loading: stringFromFile)
NSError * error;
NSString * stringFilepath = #"savefile.txt";
[stringFromFile writeToFile:stringFilepath atomically:YES encoding:NSWindowsCP1250StringEncoding error:error];
Note that in this example i use an encoding for windows (this means it uses charcters \n\r at the end of each line). Check the documentation for other types of encoding.
(See NSString documentation)
For Xcode 4, open the file you want to search, then click Edit > Find > Find and Replace, or the keyboard shortcut Command + Option + f.