来自带有特殊字符的 macOS 应用程序的 ADB 命令



我想通过 macOS 应用程序中的adb命令从我的安卓设备中提取文件。

下面的代码一切都可以完美运行,除了我要拉取的文件的名称包含特殊字符,如德语变音符号 (äöüÄÖÜ)。

我收到此错误:adb: error: failed to stat remote object '/storage/emulated/0/Download/Böse': No such file or directory.

但是当我使用命令adb pull /storage/emulated/0/Download/Böse ~/DesktopTerminal.app,文件将被拉到我的计算机上。

奇怪的是,如果我从 Xcode 控制台输出中复制子字符串/storage/emulated/0/Download/Böse,该命令在Terminal.app内也不起作用,直到我删除ö并将其替换为键盘输入中的ö

我尝试用 unicode 表示u{00f6}替换ö,但这没有效果(但控制台输出仍然显示ö但"错误"编码。

// Configure task.
let task = Process()
task.launchPath = "~/Library/Android/sdk/platform-tools/adb"
task.arguments = ["pull", "/storage/emulated/0/Download/Böse", "~/Desktop"]
// Configure pipe.
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
// Run task.
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
// adb: error: failed to stat remote object '/storage/emulated/0/Download/Böse': No such file or directory
print(output)

我在文档中找到了以下内容,Process如何处理我提供的参数:

NSTask 对象将参数中的路径和字符串转换为适当的 C 样式字符串(使用 fileSystemRepresentation),然后通过 argv[] 将它们传递给任务。参数中的字符串不进行 shell 扩展,因此不需要做特殊引用,并且 shell 变量(如 $PWD)不会被解析。

似乎我不是唯一一个遇到此问题的人,我找到了以下解决方法: 如何解决 NSTask 调用 -[NSString fileSystemRepresentation] 作为参数,但我无法让它与 Swift 一起使用。

作为一种解决方法,我现在将 adb 命令写入文件并从应用程序中的 bash 命令执行它。

let source = "/storage/emulated/0/Download/Böse"
let destination = "~/Desktop"
guard let uniqueURL = URL(string: destination + "/" + ProcessInfo.processInfo.globallyUniqueString) else { return }
// Write command to file
let scriptContent = "#!/bin/bashn~/Library/Android/sdk/platform-tools/adb pull -a "" + source + "" "" + destination + """
try? scriptContent.write(to: uniqueURL, atomically: false, encoding: .utf8)
// Configure task.
let task = Process()
task.environment = ["LC_ALL": "de_DE.UTF-8", "LANG": "de_DE.UTF-8"]
task.launchPath = "/bin/bash"
task.arguments = [uniqueURL.path]
// Configure pipe.
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
try? task.run()
// Run task.
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
print(output)

尽管这目前有效,但它不是一个令人满意的解决方案,因为它不是很优雅,效率也不高,所以欢迎任何改进或更好的答案。

相关内容

最新更新