MacOS 开发 - NSWorkspace

简介

NSWorkspace继承自NSObject,属于AppKit.framework。一个NSWorkspace对象可以启动其他应用程序和执行各种文件处理服务。
NSWorkspace 为应用程序提供如下服务:
1)打开,操作文件/设备,获取文件/设备信息
2)跟踪文件,设备以及数据库的变动
3)设置或获取文件的 Finder 信息
4)操作应用程序。

一、操作应用程序

常用API

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

hideOtherApplications - 隐藏其他发送者的所有应用程序

使用

1、打开pages,numbers

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

二、打开文件

常用API

openURL:,打开指定的URL;
openFile: ,根据文件类型使用默认的app打开指定的文件
openFile:withApplication: ,使用指定的app打开文件
openFile:withApplication:andDeactivate: 使用指定的app打开文件, andDeactivate传入YES,如果发送请求前app在后台禁用,允许已经打开的app到前台。

使用方法

1、openURL 打开网页

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

2、openURL 发送邮件

#pragma mark - 使用safari发邮件
- (void)sendEmail{
    NSURL *url = [NSURL URLWithString:@"mailto:[email protected]"];
    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 来转化。使用 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 打开偏好设置

[[NSWorkspace sharedWorkspace] openFile:@"/System/Library/PreferencePanes/Security.prefPane”];
上面的是打开万能辅助的界面的代码。
如果你想打开,其他的界面可以替换后面的 Security.prefPane。
我们可以打开目录 /System/Library/PreferencePanes 一看

performFileOperation:source:destination:files:tag: 在一个特定的目录中执行对一组文件的文件操作,可操作类型有
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: 根据文件夹全路径选择文件
duplicateURLs:completionHandler: - 以 Finder 操作的相同方式异步复制指定的 URL。
recycleURLs:completionHandler: - 以 Finder 操作的相同方式,移动指定的url到废纸篓
activateFileViewerSelectingURLs: 激活Finder,根据指定的多个文件,打开一个或者多个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];//根据文件夹全路径 选择文件
}

我感觉 inFileViewerRootedAtPath: 应该很好用,不过博主调用失败了,有知道的同学,希望能够告诉我,我的方法是:
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描述文件系统。
isFilePackageAtPath: 确定指定的路径是不是一个文件包。

@property(readonly, strong) NSRunningApplication frontmostApplication; 返回最前面的应用程序,接收事件的app。
@property(readonly, copy) NSArray runningApplications; , 返回正在运行的app

1、fullPathForApplication 获取指定app的全路径

- (void)getFullPathForApplication {
   NSString *fullPath = [[NSWorkspace sharedWorkspace] fullPathForApplication:@"Pages"];
    NSLog(@"fullPath:%@",fullPath);
}
打印结果:
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描述文件系统
    [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);
}
打印结果
>> gather file info:
     AppName: /Applications/Preview.app
     type: png
     removeable: 0
     writeable: 1
     unmountable: 0
     description: hfs
     fileSystemType: hfs

五、操纵统一类型标识符信息 Uniform Type Identifier

typeOfFile:error: 返回指定文件的统一类型标识符,如果他能被探测到的话。
localizedDescriptionForType: 返回指定统一类型标识符的本地化描述
preferredFilenameExtensionForType: 返回指定统一类型标识符的文件后缀名
filenameExtension:isValidForType: 返回是否指定文件后缀是否适合统一类型标识符
type:conformsToType: 返回一个布尔值表示第一个统一类型标识符是否符合第二个统一类型标识符。
URLForApplicationWithBundleIdentifier: 返回相对于app指定标识符的url

六、管理图标

iconForFile: 返回指定文件包含的图标图片
iconForFileType: 返回指定类型指定文件包含的图标文件
iconForFiles: 返回指定多个文件包含的图标文件
setIcon:forFile:options: 带着附加的选项,为指定的路径文件或者目录 设置图标

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]];//不显示图片,而是显示 图片类型文件 对应的图标
    
    NSString *path2 = [workspace fullPathForApplication:@"Safari"];
    self.imgView1.image  = [workspace iconForFile:path2];
    
    NSImage *xcodeIcon = [workspace iconForFileType:@"xcodeproj"];
    self.imgView2.image = xcodeIcon;
}

2、setIcon 设置文件预览图标

sqlist 原来是没有预览图的,我们改为系统图标
系统图标的方法,可参考:
http://blog.csdn.net/lovechris00/article/details/77994908

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

七、卸载设备

unmountAndEjectDeviceAtPath: 在指定的路径卸载和弹出设备。
unmountAndEjectDeviceAtURL:error: 尝试弹出安装在指定的路径的卷。

八、管理Bundles

  • absolutePathForAppBundleWithIdentifier: 返回一个app bundle在文件系统的绝对路径
  • launchAppWithBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifier: 指定 bundleIdentifier 启动该应用程序。
  • openURLs:withAppBundleIdentifier:options:additionalEventParamDescriptor:launchIdentifiers: 从一个url数组打开一个或者多个文件

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,为桌面设置图片
  • desktopImageOptionsForScreen: 返回给定屏幕的桌面图片选项
  • 执行Finder Spotlight搜索
    showSearchResultsForQueryString: 显示 Spotlight 搜索结果窗口

1、setDesktopImageURL 设置桌面背景图

- (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(@"设置背景图失败:%@",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);
}

十、执行 Finder Spotlight 搜索

1、showSearchResultsForQueryString: 显示 Spotlight 搜索结果窗口

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

十一、Finder文件标签

@property(readonly, copy) NSArray *fileLabelColors; 返回相应文件在颜色数组中的文件标签

fileLabels 返回标签的数组

十二、跟踪文件系统的改变

  • noteFileSystemChanged: 通知workspace对象,文件系统在指定的路径发生变化。
    注销前请求额外的时间
  • extendPowerOffBy: 当关闭电源注销用户的时候,请求系统等待自定数量的时间
    支持可访问性
@property(readonly) BOOL accessibilityDisplayShouldDifferentiateWithoutColor; 一个布尔值,该值指示应用程序是否应避免通过单独的颜色展示信息。
@property(readonly) BOOL accessibilityDisplayShouldIncreaseContrast; 一个布尔值,该值指示应用程序是否应该显示高对比度的用户界面。

十三、常用用户信息字典的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

你可能感兴趣的:(MacOS 开发 - NSWorkspace)