文本文件未创建

时间:2015-12-12 02:42:17

标签: objective-c cocoa scripting applescript

int main(int argc, const char * argv[]) {
    NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"tell application \"Safari\" to return URL of tabs of window 1"];
    NSDictionary *scriptError = nil;
    NSAppleEventDescriptor *descriptor = [script executeAndReturnError:&scriptError];
    if(scriptError) {
        NSLog(@"Error: %@",scriptError);
    } else {
        NSAppleEventDescriptor *listDescriptor = [descriptor  coerceToDescriptorType:typeAEList];
        NSMutableArray *result = [[NSMutableArray alloc] init];
        for (NSInteger i = 1; i <= [listDescriptor numberOfItems]; ++i) {
            NSAppleEventDescriptor *URLDescriptor = [listDescriptor descriptorAtIndex:i];
            [result addObject: URLDescriptor.stringValue];
    }
    NSString *content = [result componentsJoinedByString:@","];

    NSData *fileContents = [content dataUsingEncoding:NSUTF8StringEncoding];
    [[NSFileManager defaultManager] createFileAtPath:@"~/Desktop/foo.txt"
                                            contents:fileContents
                                          attributes:nil];
    NSLog(@"Result: %@", [result copy]);
    }
    return 0;
}

我的代码现在的问题是,每件事情都正常工作(打印出URL数组等等。但是当我检查时,我看到foo.txt没有被创建?我的应用程序出了什么问题。

我的另一个问题是关于我的AppleScript(第二行),我只能获得窗口1的URL,我怎样才能获得所有窗口?

任何答案都将不胜感激!

3 个答案:

答案 0 :(得分:0)

Tilde扩展由Unix shell处理。 Objective-C不会自动将该字符串扩展为Desktop目录的绝对路径。

您需要使用stringByExpandingTildeInPath

NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES);

createFileAtPath构建正确的路径。

答案 1 :(得分:0)

要回答第二个问题,let yourNumber = 343234729; let decomposed = yourNumber.toString(2).split('').reverse().map((bit, index) => bit === '1' ? 1 << index : 0).filter(x => x > 0); 应该返回一个URL字符串列表列表(告诫应用程序的Apple事件支持中的任何错误/限制)。

您可能还需要考虑使用AppleScriptObjC网桥,它可以为您完成所有数据转换和调用工作。虽然仍然不理想,但它不像NSAppleScript / NSAppleEventDescriptor那样令人沮丧乏味,或者像ScriptingBridge那样令人沮丧地失败,因此通常是最简单,最可靠的方式来与#Apple; AppleScriptable&#34;来自ObjC的应用程序。

答案 2 :(得分:0)

要回答您的第一个问题,您可以使用:

[content writeToFile:[NSHomeDirectory() stringByAppendingString: @"/Desktop/foo.txt"]
     atomically:YES
       encoding:NSUTF8StringEncoding
          error:nil]

而不是:

NSData *fileContents = [content dataUsingEncoding:NSUTF8StringEncoding];
[[NSFileManager defaultManager] createFileAtPath:@"~/Desktop/foo.txt"
                                        contents:fileContents
                                      attributes:nil];

content是您在代码中使用的变量。