swift - 如何将日期信息传递给 AppleScript?

标签 swift applescript nsapplescript nsappleeventdescriptor

我正在制作一个可以通过 NSAppleScript 运行 AppleScript 的应用程序。 一切都很好,但我一直无法弄清楚如何将日期信息从我的应用程序传递到 AppleScript。 (因为 AppleScript 有日期类型,我想这是可能的) 我将参数传递给 AppleScript 的方式是通过 NSAppleEventDescriptor。我从 Google 了解到我可以将它作为 typeLongDateTime 类型传递:

- (id)initWithDate:(NSDate *)date {
     LongDateTime ldt;  
     UCConvertCFAbsoluteTimeToLongDateTime(CFDateGetAbsoluteTime((CFDateRef)date), &ldt);
     return [self initWithDescriptorType:typeLongDateTime
                                   bytes:&ldt
                                  length:sizeof(ldt)];
}

不幸的是,LongDateTime 类型早已消失,因为我使用的是 Swift 并且在 OS X 10.10 下。甚至核心服务函数 UCConvertCFAbsoluteTimeToLongDateTime 也已从 10.10.3 中删除。

现在我卡住了。

您有什么启发灵感的想法吗?

最佳答案

LongDateTime 似乎是一个带符号的 64 位整数,它表示 日期 d 作为自格林威治标准时间 1904 年 1 月 1 日以来的秒数,由时区偏移量调整 对于本地时区的 d(包括夏令时 如果 DST 在 d 处于事件状态,则偏移。

对于我测试的所有日期(冬令时和夏令时),以下代码给出与您的 Objective-C 代码相同的结果。

class DateEventDescriptor : NSAppleEventDescriptor {

    convenience init?(date : NSDate) {
        let secondsSince2001 = Int64(date.timeIntervalSinceReferenceDate)
        var secondsSince1904 = secondsSince2001 + 3061152000
        secondsSince1904 += Int64(NSTimeZone.localTimeZone().secondsFromGMTForDate(date))
        self.init(descriptorType: DescType(typeLongDateTime),
            bytes: &secondsSince1904, length: sizeofValue(secondsSince1904))
    }
}

Swift 3 更新:

class DateEventDescriptor : NSAppleEventDescriptor {

    convenience init?(date: Date) {
        let secondsSince2001 = Int64(date.timeIntervalSinceReferenceDate)
        var secondsSince1904 = secondsSince2001 + 3061152000
        secondsSince1904 += Int64(NSTimeZone.local.secondsFromGMT(for: date))
        self.init(descriptorType: DescType(typeLongDateTime),
                  bytes: &secondsSince1904, length: MemoryLayout.size(ofValue: secondsSince1904))
    }
}

ma​​cOS 10.11 更新:

从 macOS 10.11 开始,有一个

 NSAppleEventDescriptor(date: Date)

初始化器,因此不再需要上述解决方法。 (感谢@Wevah 提供此信息。)

关于swift - 如何将日期信息传递给 AppleScript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30590142/

相关文章:

swift - 从 NSData 到 Swift 2 中的 SecKeyRef

objective-c - 以编程方式取消静音OSX中的音频输入(麦克风)

objective-c - 使用 Applescript 创建一个简单的菜单栏应用程序

cocoa - -[NSAppleScript执行并返回错误:] gives error with script that works in AppleScript Editor

swift - 如何在 Swift 中比较随机数

ios - UIButton 标题标签的不同大小的字符串

swift - 为什么 iPhone XS 在实时使用相机时的 CPU 性能比 iPhone 6S Plus 差?

excel - 如何使用 Applescript 从 Excel 中的单元格引用中提取行号?

swift - 将 AppleScript 字符串列表转换为 Swift 数组