简体   繁体   中英

OSX Application, get file data that user selected using NSOpenPanel

I am new to developing OSX Applications. I normally do iOS Apps, so alot of the concepts carry over. However, I cannot quite seem to figure out why I cannot retrieve the data of a file on my system.

Is there something that needs to be done first in order to read files on the users system?

Here is what I have:

- (IBAction)btnBrowse:(id)sender {
    NSOpenPanel *panel = [NSOpenPanel openPanel];

    [panel beginWithCompletionHandler:^(NSInteger result){

        if (result == NSFileHandlingPanelOKButton) {
            //Get the file url user selected
            NSURL *file = [[panel URLs] objectAtIndex:0];

            //Get the file data
            NSError *error;
            NSString *fileData = [NSString stringWithContentsOfFile:[NSString stringWithFormat:@"%@", file] encoding:NSUTF8StringEncoding error:&error];

            //This returns null
            NSLog(@"%@", fileData);

            //This says that the file does not exist
            NSLog(@"Error: %@", error.localizedDescription);
        }
    }];
}

NSOpenPanel returns NSURL objects, the easiest solution is to use the NSURL related API

NSString *fileData = [NSString stringWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];

If you don't know the text encoding you could use this API, if the reading succeeds, encoding contains the used encoding.

NSStringEncoding encoding;    
NSString *fileData = [NSString stringWithContentsOfURL:file usedEncoding:&encoding error:&error];

使用-[NSURL path]方法而不是直接调用“文件”,因为它是NSURL,而不是NSString。

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