Objective c Xcode桌面目录和writeToFile:始终使用不同的应用程序名称
我正在创建一个应用程序,截图的mac桌面 但我有两个问题: 桌面的“全局”目录是什么 我的电脑中有Objective c Xcode桌面目录和writeToFile:始终使用不同的应用程序名称,objective-c,macos,directory,writetofile,Objective C,Macos,Directory,Writetofile,我正在创建一个应用程序,截图的mac桌面 但我有两个问题: 桌面的“全局”目录是什么 我的电脑中有/Users/miguelcosta/Desktop/,但我想要一个适用于所有Mac电脑的目录 我的第二个问题是: 当你截图时,他会在你的桌面上创建一个名为Result.jpg的图像。然而,当你拍摄另一张截图时,他会替换上一张截图。。。所以我在想我怎么能总是用不同的名字保存这些图片 这是我的密码: NSString*targetPath=@“/Users/miguelcosta/Desktop/Re
/Users/miguelcosta/Desktop/
,但我想要一个适用于所有Mac电脑的目录
我的第二个问题是:
当你截图时,他会在你的桌面上创建一个名为Result.jpg的图像。然而,当你拍摄另一张截图时,他会替换上一张截图。。。所以我在想我怎么能总是用不同的名字保存这些图片
这是我的密码:
NSString*targetPath=@“/Users/miguelcosta/Desktop/Result.jpg”
谢谢你的帮助 下面是一段代码片段。。。另请参阅本主题:
你所说的适用于所有Mac电脑的目录是什么意思?您的意思是,对于所有用户?使用NSString的路径属性和方法,如
lastPathComponent
和pathExtension
或使用NSURL。编辑:NSArray*parts=[[filePath lastPathComponent]Components通过字符串分离:@]代码>
NSData *imageData = [newImage TIFFRepresentation];
NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imageData];
NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] forKey:NSImageCompressionFactor];
imageData = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
[imageData writeToFile:targetPath atomically:NO];
#import "ViewController.h"
@interface ViewController()
{
NSInteger _count;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_count = 1;
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES );
NSString* desktopPath = [paths objectAtIndex:0];
NSString *fileName = @"Result.jpg";
NSString *filePath = [NSString stringWithFormat:@"%@/%@", desktopPath, fileName];
filePath = [self filePathWithPath:filePath];
// write to file now using filePath ...
}
// generate new name ...
- (NSString*)filePathWithPath:(NSString*)filePath
{
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSArray *parts = [[filePath lastPathComponent] componentsSeparatedByString:@"."];
NSString *name = parts[0];
NSString *ext = parts[1];
filePath = [self filePathWithPath:[NSString stringWithFormat:@"%@/%@%ld.%@", filePath, name, _count++, ext]];
}
return filePath;
}
@end