【发布时间】:2018-09-19 17:30:58
【问题描述】:
我的最终问题是关于使用 XCTest 和 Swift4(在与电视设备配对的 MacBook 上运行)保存 AppleTV 应用程序的屏幕截图,但我什至无法将简单的文本字符串写入本地文件。如果我能让这个简单的文件保存工作,我希望我能解决截图问题。 (抱歉让这看起来像两个问题,但它们似乎是相关的,并且是我的故障排除工作的结果。)
首先,根据我在网上某处找到的示例代码,这是我尝试使用屏幕截图执行的操作:
let appshot = XCUIApplication().windows.firstMatch.screenshot()
let shotpath = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask)[0].appendingPathComponent("appshot.png")
let shotpathUrl = URL(string: "file://\(shotpath)")
print("Saving to: \(shotpath)")
do {
try appshot.pngRepresentation.write(to: shotpathUrl!)
} catch {
print("Failed saving screenshot due to \(error)")
}
这给了我以下输出:
Saving to: file:///var/mobile/Containers/Data/Application/77D52C66-353B-4029-97D5-48E6BAE35C92/Downloads/appshot.png
Failed saving screenshot due to Error Domain=NSCocoaErrorDomain Code=4 "The file “appshot.png” doesn’t exist." UserInfo={NSFilePath=///var/mobile/Containers/Data/Application/77D52C66-353B-4029-97D5-48E6BAE35C92/Downloads/appshot.png, NSUnderlyingError=0x1c405bc60 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
当然,该文件不存在,因为这是我正在尝试创建的文件。但是 /var/mobile 也不存在于我的笔记本电脑上——看起来 FileManager 正在构建的路径可能存在于 AppleTV 设备上,但我希望它在我的笔记本电脑上执行我的测试脚本。
所以我退出了一个更简单的案例,即使这样也给我带来了问题:
let str = "This is a test"
let path = "file:///Users/haljor/foo.txt"
let pathUrl = URL(string: path)!
print("Path: \(path)")
print("URL: \(pathUrl)")
do {
try str.write(to: pathUrl, atomically: true, encoding: .utf8)
} catch {
print("Caught error writing to \(pathUrl): \(error)")
}
这是输出:
Path: file:///Users/haljor/foo.txt
URL: file:///Users/haljor/foo.txt
Caught error writing to file:///Users/haljor/foo.txt: Error Domain=NSCocoaErrorDomain Code=4 "The folder “foo.txt” doesn’t exist." UserInfo={NSURL=file:///Users/haljor/foo.txt, NSUserStringVariant=Folder, NSUnderlyingError=0x1c40553f0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}
在这里,它似乎正在尝试写入我指定路径的文件夹,而不是文件。显然,在每种情况下,我都不理解某些东西。
我真的不喜欢使用完全指定的路径还是使用 FileManager 的东西——它只需要放在我的笔记本电脑(而不是电视设备)上的某个地方。我错过了什么?
【问题讨论】: