0

在终端这有效:

/usr/bin/curl --connect-timeout 10 --max-time 60 https://en.wikipedia.org/wiki/The_Beatles -o /Users/username/Desktop/wikiData

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  909k  100  909k    0     0  2025k      0 --:--:-- --:--:-- --:--:-- 2025k

但在 Xcode 中,这不会:

let task = Process()
let pipe = Pipe()
task.launchPath = "/usr/bin/curl"
task.arguments = ["--connect-timeout","10","--max-time","60","en.wikipedia.org/wiki/The_Beatles","-o","/Users/username/Desktop/wikiData"]
task.standardOutput = pipe
task.launch()
task.waitUntilExit()

我明白了:

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
Warning: Failed to create the file /Users/username/Desktop/wikiData: 
Warning: Operation not permitted
curl: (23) Failed writing received data to disk/application

如何授予 curl 写入磁盘的权限?在沙箱中,我检查了“网络传入/传出”以便能够与维基百科交谈,并设置“文件访问/用户选择的文件/读/写”,但这似乎不适用于 curl。如果我离开“-o ...”,我不会出错。但我似乎也没有得到任何数据。想法?谢谢。

4

2 回答 2

1

无法写入输出的原因cURL是它必须具有沙盒不允许的权限。您可能应该采用stdoutvia 管道,cURL然后尝试以原子方式写入数据。

let filePath = "/Users/username/Desktop/wikiData/the_beatles.txt"
let task = Process()

task.launchPath = "/usr/bin/curl"
task.arguments = ["--connect-timeout","10","--max-time","60","https://en.wikipedia.org/wiki/The_Beatles"]

// stdout everything to pipe
let pipe = Pipe()
task.standardOutput = pipe

task.launch()

// collect output
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = NSString(data: data, encoding: String.Encoding.utf8.rawValue)

let str = output!
let filename = URL(fileURLWithPath: filePath)

do {
    try str.write(to: filename, atomically: true, encoding: String.Encoding.utf8.rawValue)
} catch {
    print("failed.")
}

可能有更简洁的方法来实现这一点(例如URLSession),尽管这至少应该让您了解如何在沙盒应用程序的限制内写入数据。

于 2020-04-06T22:13:11.400 回答
0

我不得不改变

let filePath = "/Users/username/Desktop/wikiData/the_beatles.txt"

let filePath = NSHomeDirectory() + "/wikiData"

谢谢您的帮助; 现在一切正常。:-)

于 2020-04-07T20:34:37.470 回答