macOS/iOS API解説

iOS , Mac アプリケーション開発のために使われる主要フレームワークの日本語情報です。2010年代に書かれた内容です。今後更新はありません。

目次

openFile:withApplication:

INDEX>AppKit>NSWorkspace

指定したファイルを、指定したアプリケーションで開きます

Objective-C

- (BOOL)openFile:(NSString *)fullPath
 withApplication:(NSString *)appName

Swift

func openFile(_ fullPath: String,
withApplication appName: String) -> Bool

解説

指定したファイルを、指定したアプリケーションで開きます。
アプリケーションはフルパスで指定しなくてもアプリケーション名だけでいいです。
開くことができればYESを返します。
そうでなければNOを返します。

10.6からスレッドセーフです。

返り値

開けたかYES/NO
Objective-C

(BOOL)

Swift

Bool

引数

アプリケーションのフルパス
Objective-C

(NSString *)fullPath

Swift

fullPath: String

アプリケーション名
Objective-C

(NSString *)appName

Swift

appName: String

フレームワーク

ApplicationKit

クラス

NSWorkspace

使用可能

10.0

参照

openFile:
openFile:withApplication:andDeactivate:

cocoaapi.hatenablog.com

更新時のバージョン

OS X 10.10

関連記事(外部サイト)

Theocacao: Using NSWorkspace with Files

例文

Objective-C

#import "SetImage.h"

@implementation SetImage

- (IBAction)set:(id)sender
{
 //開けるファイル拡張子の配列
    NSArray      *fileTypes    = [ NSArray arrayWithObject : @"tiff" ];
    //OpenPanelを作る
    NSOpenPanel  *opPanel       = [ NSOpenPanel openPanel ];
    //OpenPanelの結果のボタン番号
    int		  opRet;
    BOOL	openResult;
        //OpenPanelでファイル選択   
    opRet = [ opPanel runModalForDirectory : NSHomeDirectory() //どこのディレクトリを出すか
                                     file : @"Pictures" //どのどのファイルを選択しておくか
                                    types : fileTypes ];//選べるファイルタイプ
    if ( opRet == NSOKButton ) {  // OPENPanelのボタンがOKなら
        openResult = [[NSWorkspace sharedWorkspace] openFile:[ opPanel filename ] withApplication:@"QuickTime Player"];
    }
}

@end

Swift

    //NSWorkspace openFile:withApplication:
    @IBAction func function004(sender: AnyObject) {
        let theWorkspace : NSWorkspace = NSWorkspace.sharedWorkspace()
        let theFilePath : NSString = NSString(string: "~/Desktop/textured.gif")
        //チルダ付きのファイルパスをフルパスに変換する
        let fileFullPath : NSString = theFilePath.stringByExpandingTildeInPath
        NSLog(fileFullPath)
        if theWorkspace.openFile(fileFullPath, withApplication:"Safari") {
            NSLog("OK")
        }else{
            NSLog("NO")
        }
    }