简体   繁体   中英

How to read macOS desktop file in cocoa app

I want to make cocoa app execute .sh file or other Operation, this my code:

- (void)viewDidLoad {
    [super viewDidLoad];
    NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);
}

- (NSString *)cmd:(NSString *)cmd
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/bash"];
    NSArray *arguments = [NSArray arrayWithObjects: @"-c", cmd, nil];
    [task setArguments: arguments];
    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];
    NSFileHandle *file = [pipe fileHandleForReading];
    [task launch];
    NSData *data = [file readDataToEndOfFile];
    return [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
}

but log error:

ls: .: Operation not permitted

how to do that?I search about macOS permit,Do I need use SMJobBless ?

change

 NSLog(@"%@",[self cmd:@"cd Desktop;ls;"]);

with

NSLog(@"%@",[self cmd:@"cd ~/Desktop; ls;"]);

Sandbox applications aren't allowed to read outside the application folder. So in order for your script to work you need to turn off Sandbox.

Also you need to change the path like Sangram S. mentioned or set the current directory to the home folder:

[task setCurrentDirectoryPath:NSHomeDirectory()];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM