MacOS 開發(fā) - NSWorkspace

簡介

NSWorkspace繼承自NSObject,屬于AppKit.framework。一個NSWorkspace對象可以啟動其他應(yīng)用程序和執(zhí)行各種文件處理服務(wù)。
NSWorkspace 為應(yīng)用程序提供如下服務(wù):
1)打開,操作文件/設(shè)備,獲取文件/設(shè)備信息
2)跟蹤文件,設(shè)備以及數(shù)據(jù)庫的變動
3)設(shè)置或獲取文件的 Finder 信息
4)操作應(yīng)用程序。

一、操作應(yīng)用程序

常用API

launchApplication: - 運行指定的app
launchApplicationAtURL:options:configuration:error: - 指定的url運行app
launchApplication:showIcon:autolaunch: - 使用附加的屬性運行指定的app

hideOtherApplications - 隱藏其他發(fā)送者的所有應(yīng)用程序

使用

1、打開pages,numbers

[[NSWorkspace sharedWorkspace] launchApplication:@"Pages"]; [[NSWorkspace sharedWorkspace] launchApplication:@"Numbers"];

二、打開文件

常用API

openURL:,打開指定的URL;
openFile: ,根據(jù)文件類型使用默認的app打開指定的文件
openFile:withApplication: ,使用指定的app打開文件
openFile:withApplication:andDeactivate: 使用指定的app打開文件, andDeactivate傳入YES,如果發(fā)送請求前app在后臺禁用,允許已經(jīng)打開的app到前臺。

使用方法

1、openURL 打開網(wǎng)頁

#pragma mark - 使用safari打開網(wǎng)頁
- (void)openUrlBySafari {
    NSURL * url = [NSURL URLWithString:@"http://blog.csdn.net/lovechris00?viewmode=contents"];
    [[NSWorkspace sharedWorkspace] openURL: url];
}

2、openURL 發(fā)送郵件

#pragma mark - 使用safari發(fā)郵件
- (void)sendEmail{
    NSURL *url = [NSURL URLWithString:@"mailto:abcdefg@163.com"];
    assert(url !=nil);
    [[NSWorkspace sharedWorkspace]openURL:url];
}

3、openURL 使用照片預覽 打開 pdf 文件

#pragma mark - 使用照片預覽 打開 pdf 文件
- (void)openPdfByDefault {
    NSString *path = @"/Users/user/Downloads/《明解C語言》.pdf";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    [[NSWorkspace sharedWorkspace] openURL: fileURL];
}

4、openURL 使用 safari 打開 pdf 文件

#pragma mark - 使用 safari 打開 pdf 文件
- (void)openPdfBySafari {
    NSString *path = @"/Users/user/Downloads/《明解C語言》.pdf";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    NSWorkspace * workspace = [NSWorkspace sharedWorkspace];
    [workspace openFile:[fileURL path] withApplication:@"Safari"];
}

5、打開 Pages 文件

如果使用 safari 打開 Pages 文件,Safari 打開后,識別到文件類型后,還是會自動打開 pages 編譯器

#pragma mark - 使用默認模式 打開 Pages 文件
- (void)openPagesByDefault {
    NSString *path = @"/Users/user/Documents/需求文檔.pages";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    [workspace openURL: fileURL];
}

6、使用代碼打開 dmg、pkg 文件

注意:url 要使用fileURLWithPath 來轉(zhuǎn)化。使用 URLWithString 就沒用了。

#pragma mark - 使用默認模式 打開 Pages 文件
 NSString *path = @"/Users/administrator/Downloads/MacCode_v1.46.dmg";
 NSString *pkgPath = @"/Users/administrator/Desktop/PKGDemo/build/PKGDemo1.pkg";
 NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
 [workspace openURL:[NSURL fileURLWithPath:pkgPath]];

7、openFile 打開偏好設(shè)置

[[NSWorkspace sharedWorkspace] openFile:@"/System/Library/PreferencePanes/Security.prefPane”];
上面的是打開萬能輔助的界面的代碼。
如果你想打開,其他的界面可以替換后面的 Security.prefPane。
我們可以打開目錄 /System/Library/PreferencePanes 一看

performFileOperation:source:destination:files:tag: 在一個特定的目錄中執(zhí)行對一組文件的文件操作,可操作類型有
NSWorkspaceMoveOperation - "Use -[NSFileManager moveItemAtURL:toURL:error:] instead.");
NSWorkspaceCopyOperation - "Use -[NSFileManager copyItemAtURL:toURL:error:] instead.");
NSWorkspaceLinkOperation - "Use -[NSFileManager linkItemAtURL:toURL:error:] instead.”);                                                                
NSWorkspaceDestroyOperation - "Use -[NSFileManager removeItemAtURL:error:] instead.”);

三、操作文件

常用API

selectFile:inFileViewerRootedAtPath: 根據(jù)文件夾全路徑選擇文件
duplicateURLs:completionHandler: - 以 Finder 操作的相同方式異步復制指定的 URL。
recycleURLs:completionHandler: - 以 Finder 操作的相同方式,移動指定的url到廢紙簍
activateFileViewerSelectingURLs: 激活Finder,根據(jù)指定的多個文件,打開一個或者多個windows并且選中他們。

使用

1、selectFile 打開文件夾并選中文件

#pragma mark - 打開文件夾并選中文件
- (void)selectFileInFinder {
    NSString * path = @"/Users/MelissaShu/Pictures/看視頻.png";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    [workspace selectFile:[fileURL path] inFileViewerRootedAtPath:nil];//根據(jù)文件夾全路徑 選擇文件
}

我感覺 inFileViewerRootedAtPath: 應(yīng)該很好用,不過博主調(diào)用失敗了,有知道的同學,希望能夠告訴我,我的方法是:
NSString *path2 = @"111.png";
NSURL *fileURL2 = [NSURL fileURLWithPath: path2];
[workspace selectFile:[fileURL2 path] inFileViewerRootedAtPath:@"/Users/MelissaShu/Pictures/"];

四、請求文件信息

常用API

getInfoForFile:application:type: 檢索指定的文件的信息。
URLForApplicationToOpenURL: 返回將用于打開給定的URL的默認的app的URL。
fullPathForApplication: 返回指定app的全路徑
getFileSystemInfoForPath:isRemovable:isWritable:isUnmountable:description:type: 用fullPath描述文件系統(tǒng)。
isFilePackageAtPath: 確定指定的路徑是不是一個文件包。

@property(readonly, strong) NSRunningApplication frontmostApplication; 返回最前面的應(yīng)用程序,接收事件的app。
@property(readonly, copy) NSArray<NSRunningApplication > runningApplications; , 返回正在運行的app

1、fullPathForApplication 獲取指定app的全路徑

- (void)getFullPathForApplication {
   NSString *fullPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"Pages"];
    NSLog(@"fullPath:%@",fullPath);
}
打印結(jié)果:
fullPath:/Applications/Pages.app

2、getInfoForFile 獲取文件信息

- (void)gatherFileInfo {
    NSString * path = @"/Users/MelissaShu/Pictures/看視頻.png";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    
    NSString *appName;
    NSString *fileType;
    
    //檢索指定的文件的信息
    [workspace getInfoForFile: [fileURL path] application: &appName type: &fileType];
    NSLog(@"appName : %@ , fileType : %@",appName,fileType);
    
    BOOL removable = NO;
    BOOL writeable = NO;
    BOOL unmountable = NO;
    
    NSString *description;
    NSString *fileSystemType;

   //用fullPath描述文件系統(tǒng)
    [workspace getFileSystemInfoForPath:[fileURL path]
                            isRemovable: &removable
                             isWritable: &writeable
                          isUnmountable: &unmountable
                            description: &description
                                   type: &fileSystemType];
    
    NSString *fileInfo = [NSString stringWithFormat:
                     @"AppName: %@\ntype: %@"
                     @"\nremoveable: %d\nwriteable: %d\nunmountable: %d"
                     @"\ndescription: %@\nfileSystemType: %@",
                     appName, fileType,
                     removable, writeable, unmountable,
                     description, fileSystemType];
    
    NSLog (@" >> gather file info:\n%@", fileInfo);
}
打印結(jié)果
>> gather file info:
     AppName: /Applications/Preview.app
     type: png
     removeable: 0
     writeable: 1
     unmountable: 0
     description: hfs
     fileSystemType: hfs

五、操縱統(tǒng)一類型標識符信息 Uniform Type Identifier

typeOfFile:error: 返回指定文件的統(tǒng)一類型標識符,如果他能被探測到的話。
localizedDescriptionForType: 返回指定統(tǒng)一類型標識符的本地化描述
preferredFilenameExtensionForType: 返回指定統(tǒng)一類型標識符的文件后綴名
filenameExtension:isValidForType: 返回是否指定文件后綴是否適合統(tǒng)一類型標識符
type:conformsToType: 返回一個布爾值表示第一個統(tǒng)一類型標識符是否符合第二個統(tǒng)一類型標識符。
URLForApplicationWithBundleIdentifier: 返回相對于app指定標識符的url

六、管理圖標

iconForFile: 返回指定文件包含的圖標圖片
iconForFileType: 返回指定類型指定文件包含的圖標文件
iconForFiles: 返回指定多個文件包含的圖標文件
setIcon:forFile:options: 帶著附加的選項,為指定的路徑文件或者目錄 設(shè)置圖標

1、iconForFile & iconForFileType 獲取圖片

- (void)getIconOfFile {
    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSString *path = @"/Users/MelissaShu/Pictures/背景圖/background0.png";
    NSURL *fileURL = [NSURL fileURLWithPath: path];
    self.imgView.image = [workspace iconForFile:[fileURL path]];//不顯示圖片,而是顯示 圖片類型文件 對應(yīng)的圖標
    
    NSString *path2 = [workspace fullPathForApplication:@"Safari"];
    self.imgView1.image  = [workspace iconForFile:path2];
    
    NSImage *xcodeIcon = [workspace iconForFileType:@"xcodeproj"];
    self.imgView2.image = xcodeIcon;
}

2、setIcon 設(shè)置文件預覽圖標

sqlist 原來是沒有預覽圖的,我們改為系統(tǒng)圖標
系統(tǒng)圖標的方法,可參考:
http://blog.csdn.net/lovechris00/article/details/77994908

 NSString *path4 = @"/Users/MelissaShu/Documents/DATA.sqlist";
    [workspace setIcon:[NSImage imageNamed:NSImageNameQuickLookTemplate] forFile:path4 options:NSExcludeQuickDrawElementsIconCreationOption];

七、卸載設(shè)備

unmountAndEjectDeviceAtPath: 在指定的路徑卸載和彈出設(shè)備。
unmountAndEjectDeviceAtURL:error: 嘗試彈出安裝在指定的路徑的卷。

八、管理Bundles

  • absolutePathForAppBundleWithIdentifier: 返回一個app bundle在文件系統(tǒng)的絕對路徑
  • launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier: 指定 bundleIdentifier 啟動該應(yīng)用程序。
  • openURLs:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers: 從一個url數(shù)組打開一個或者多個文件

1、launchAppWithBundleIdentifier 通過BundleID 打開Safari

#pragma mark - 通過BundleID 打開APP
- (void)launchApplicationWithBundleID {
    NSWorkspace * workspace = [NSWorkspace sharedWorkspace];
    BOOL wasLaunched = [workspace launchAppWithBundleIdentifier: @"com.apple.Safari"
                       options: NSWorkspaceLaunchWithoutActivation
                       additionalEventParamDescriptor: NULL
                       launchIdentifier: nil];
    
    if( wasLaunched ){
        NSLog (@"Safari was launched");
    }else{
        NSLog (@"Safari was not launched");
    }
    NSArray * apps = [workspace valueForKeyPath:@"launchedApplications.NSApplicationName"];
    NSLog(@"Launched Applications:\n%@", apps);
}

九、管理桌面圖片

  • desktopImageURLForScreen: 返回給定屏幕的桌面圖片
  • setDesktopImageURL:forScreen:options:error: 指定給定的屏幕與圖片url,為桌面設(shè)置圖片
  • desktopImageOptionsForScreen: 返回給定屏幕的桌面圖片選項
  • 執(zhí)行Finder Spotlight搜索
    showSearchResultsForQueryString: 顯示 Spotlight 搜索結(jié)果窗口

1、setDesktopImageURL 設(shè)置桌面背景圖

- (void)setDesktopImage {
//    NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"wallpaper" ofType:@"jpg"];
//    NSURL* imageURL = [NSURL fileURLWithPath:imagePath isDirectory:NO];
     NSURL *imageURL = [[NSBundle mainBundle] URLForResource:@"background0" withExtension:@"jpg"];
      NSError *error;
      [[NSWorkspace sharedWorkspace] setDesktopImageURL:imageURL forScreen:[NSScreen mainScreen] options:nil error:&error];
    if (error) {
        NSLog(@"設(shè)置背景圖失?。?@",error);
    }
}

2、desktopImageURLForScreen & desktopImageOptionsForScreen 獲取桌面背景圖&背景圖信息

- (void)getDestopImage {
    NSURL *url = [[NSWorkspace sharedWorkspace] desktopImageURLForScreen:[NSScreen mainScreen]];
    NSImage *img = [[NSImage alloc]initWithContentsOfURL:url];
    NSLog(@"url:%@",url);
    self.imgView.image = img;

    NSDictionary *dic = [[NSWorkspace sharedWorkspace] desktopImageOptionsForScreen:[NSScreen mainScreen]];
    NSLog(@"當前桌面背景圖信息:%@",dic);
}

十、執(zhí)行 Finder Spotlight 搜索

1、showSearchResultsForQueryString: 顯示 Spotlight 搜索結(jié)果窗口

- (void)searchFinder {
    [[NSWorkspace sharedWorkspace] showSearchResultsForQueryString:@"測試"];
}

十一、Finder文件標簽

@property(readonly, copy) NSArray<NSColor *> *fileLabelColors; 返回相應(yīng)文件在顏色數(shù)組中的文件標簽

fileLabels 返回標簽的數(shù)組

十二、跟蹤文件系統(tǒng)的改變

  • noteFileSystemChanged: 通知workspace對象,文件系統(tǒng)在指定的路徑發(fā)生變化。
    注銷前請求額外的時間
  • extendPowerOffBy: 當關(guān)閉電源注銷用戶的時候,請求系統(tǒng)等待自定數(shù)量的時間
    支持可訪問性
@property(readonly) BOOL accessibilityDisplayShouldDifferentiateWithoutColor; 一個布爾值,該值指示應(yīng)用程序是否應(yīng)避免通過單獨的顏色展示信息。
@property(readonly) BOOL accessibilityDisplayShouldIncreaseContrast; 一個布爾值,該值指示應(yīng)用程序是否應(yīng)該顯示高對比度的用戶界面。

十三、常用用戶信息字典的keys

@“NSApplicationPath”
app的全路徑,一個NSString對象

@“NSApplicationName”
app的名稱,一個NSString對象

@“NSApplicationBundleIdentifier”
app的bundle identifier,一個NSString對象

@“NSApplicationProcessIdentifier”
object. app的進程id,一個NSNumber對象

@“NSApplicationProcessSerialNumberHigh”
高長度的進程序列號(PSN),一個NSNumber對象

@“NSApplicationProcessSerialNumberLow”
低長度的進程序列號(PSN), 一個NSNumber對象

原文鏈接:https://blog.csdn.net/lovechris00/article/details/78128475

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容