简体   繁体   中英

opening files with different extensions with Cocoa

I have an NSDocument based app that already handles *.txt files. I can drag and drop those files in the dock and my app will launch correctly.

Now I want to be able to open *.text files too. So I have added:

<key>CFBundleTypeExtensions</key>
    <array>
        <string>.txt</string>
        <string>.text</string>
    </array>

to my *plist

However I can't open *.text files by drag&dropping them in the dock. (I can do MyApp> File>Open> myFile.text ) I can open *.txt as usual, and drag and drop them in the dock.

I have tried implementing these NSApp delegate methods but now I get an error and I can't open any kind of file.

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename{
    NSURL *url = [NSURL URLWithString:filename];
    NSError *error = nil;
    [[NSDocumentController sharedDocumentController] openDocumentWithContentsOfURL:url display:YES error:&error];
    if (error) {
        NSLog(@"error: %@", [error localizedDescription]);
        error = nil;
        return NO;
    }
    return YES;
}

- (void)application:(NSApplication *)sender openFiles:(NSArray *)filenames{
    for (NSString *filename in filenames) {
        [self application:sender openFile:filename];
    }
}

Error:

typeForContentsOfURL:error: must be overridden for your application to support non-'file:' URLs.

I am not subclassing NSDocumentController, so do I really need to? or is there a better/easier way of doing this?

Thanks in advance

The file extensions in the Info.plist file should not contain a period character ( . ). What happens if you do this?:

<key>CFBundleTypeExtensions</key>
    <array>
        <string>txt</string>
        <string>text</string>
    </array>

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