Objective-C: Как удалить несколько файлов с правами администратора?

Я пытаюсь удалить несколько файлов с помощью сценария Apple (приведенного ниже), но он не работает и выдает следующую ошибку:

Ожидаемое выражение, но обнаружен неизвестный токен.

Вот мой код:

{
    ///this string will be a contact of all the paths saperated by ' '
    NSString* removingLocationInString = @"";
    ///for loop in order to concat all the string(paths) in one string
    for (NSString* str in locations) {

        removingLocationInString = [NSString stringWithFormat:@"%@ \"%@\"", removingLocationInString, str];
    }

    ///creating the command that will be run from apple script
    ///e.g. rm "~/user/vikas/desktop/file.txt" "~/user/vikas/desktop/file2.txt"
    NSString* command = [NSString stringWithFormat:@"rm %@", removingLocationInString];


    [self runScriptAsAdmin:command];

}

-(BOOL)runScriptAsAdmin:(NSString*) fullScript
{
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", fullScript],
                          nil];


    NSString * output = nil;
    NSString * processErrorDescription = nil;



    NSDictionary *errorInfo = [NSDictionary new];
    NSString *script =  [NSString stringWithFormat:@"do shell script \"%@\" with administrator privileges", fullScript];

    NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
    NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];

    // Check errorInfo
    if (! eventResult)
    {
        // Describe common errors
        NSString *errorDescription = nil;
        if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
        {
            NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
            if ([errorNumber intValue] == -128)
                errorDescription = @"The administrator password is required to do this.";
        }

        // Set error message from provided message
        if (errorDescription == nil)
        {
            if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
                errorDescription =  (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
        }

        return NO;
    }
    else
    {
        // Set output to the AppleScript's output
        NSString *output = [eventResult stringValue];
        return YES;

    }

    return NO;
}

Вот скрипт, который создается

сделать скрипт оболочки "rm "/Users/vikas/.Trash/.DS_Store" "/Users/vikas/.Trash/SimpleCocoaBrowser 2.zip" "/Users/vikas/.Trash/SimpleCocoaBrowser 3.zip" "/Users/vikas /.Trash/SimpleCocoaBrowser 4 4.55.07 pm.zip" "/Users/vikas/.Trash/SimpleCocoaBrowser 4.zip"" с правами администратора


person Vikas Bansal    schedule 02.02.2016    source источник
comment
Почему вы не удаляете файлы с помощью функции NSFileManager removeItemAtPath:error:?   -  person ATLief    schedule 19.05.2016


Ответы (1)


В функцию runScriptAsAdmin добавьте следующую строку:

/// if there are " in script then then make it \"
    fullScript = [fullScript stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

Фактический сценарий Apple должен быть следующим:

выполнить сценарий оболочки "rm \"/Users/vikas/.Trash/SimpleCocoaBrowser 2.zip\" \"/Users/vikas/.Trash/SimpleCocoaBrowser 3.zip\" \"/Users/vikas/.Trash/SimpleCocoaBrowser 4. zip\"" с правами администратора

person Vikas Bansal    schedule 02.02.2016