Какао / Obj-C - открыть файл при перетаскивании его на значок приложения - PullRequest
7 голосов
/ 17 марта 2011

В настоящее время на интерфейсе моего приложения есть кнопка, позволяющая открыть файл, вот мой открытый код:

В моем app.h:

- (IBAction)selectFile:(id)sender;

В моем app.m:

@synthesize window;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

}

- (IBAction)selectFile:(id)sender {

    NSOpenPanel *openPanel  = [NSOpenPanel openPanel];
    NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil];

    NSInteger result  = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];

    if(result == NSOKButton){

        NSString * input =  [openPanel filename];

Как я могу отредактировать свой код, чтобы разрешить его открытие с помощью перетаскивания значка приложения?
Примечание. Я отредактировал файл .plist и добавил строку для «xml», но она изменила что-либо, и я получил ошибку, когда мой файл упал на иконку.
Примечание 2: я связал «Файл -> Открыть ...» с файлом selectFile: который ссылается на мой код
Примечание 3: Мое приложение не является приложением на основе документов


Спасибо за вашу помощь!
Miskia

1 Ответ

16 голосов
/ 17 марта 2011

Сначала добавьте правильные расширения для CFBundleDocumentTypes в файле .plist.

Далее внедрить следующих делегатов:
- приложение: openFile: (один файл удален)
- приложение: openFiles: (несколько файлов удалено)

Справка:
Ссылка на протокол NSApplicationDelegate

Ответ на комментарий:

Шаг за шагом пример, надеюсь, все прояснит:)

Добавить в файл .plist:

 <key>CFBundleDocumentTypes</key>
        <array>
            <dict>
                <key>CFBundleTypeExtensions</key>
                <array>
                    <string>xml</string>
                </array>
                <key>CFBundleTypeIconFile</key>
                <string>application.icns</string>
                <key>CFBundleTypeMIMETypes</key>
                <array>
                    <string>text/xml</string>
                </array>
                <key>CFBundleTypeName</key>
                <string>XML File</string>
                <key>CFBundleTypeRole</key>
                <string>Viewer</string>
                <key>LSIsAppleDefaultForType</key>
                <true/>
            </dict>
        </array>

Добавить в ... AppDelegate.h

- (BOOL)processFile:(NSString *)file;
- (IBAction)openFileManually:(id)sender;

Добавить в ... AppDelegate.m

- (IBAction)openFileManually:(id)sender;
{
    NSOpenPanel *openPanel  = [NSOpenPanel openPanel];
    NSArray *fileTypes = [NSArray arrayWithObjects:@"xml",nil];
    NSInteger result  = [openPanel runModalForDirectory:NSHomeDirectory() file:nil types:fileTypes ];
    if(result == NSOKButton){
        [self processFile:[openPanel filename]];
    }
}

- (BOOL)application:(NSApplication *)theApplication openFile:(NSString *)filename
{
    return [self processFile:filename];
}

- (BOOL)processFile:(NSString *)file
{
    NSLog(@"The following file has been dropped or selected: %@",file);
    // Process file here
    return  YES; // Return YES when file processed succesfull, else return NO.
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...