关于ios:由于不支持URL类型http,因此无法打开文件

The file couldn’t be opened because URL type http isn’t supported

使用iOS 9,我尝试使用NSFileManager's moveItemAtURL

1
2
3
4
5
6
7
do {
    print(localURL) // http://localhost:3000/api/v1/activities
    print(cacheFile) // file:///Users/kyledecot/Library/Developer/CoreSimulator/Devices/35C03988-D8F5-42E5-AB35-B99BE461EEAE/data/Containers/Data/Application/69593B3A-F764-4BC3-89AD-72B701BF85C8/Library/Caches/activities.json
    try fileManager.moveItemAtURL(localURL, toURL: cacheFile)
} catch let error as NSError {
    print(error)
}

捕获错误时,我得到:

Error Domain=NSCocoaErrorDomain Code=262"The file"activities" couldn’t be opened because URL type http isn’t supported." UserInfo={NSURL=http://localhost:3000/api/v1/activities}

更新#1

我已经在Info.plist中添加了适当的值,以确保ATS满意(请参见屏幕截图)。 奇怪的是,我能够使用HTTP(通过dataTaskWithRequest:)从本地服务器下载数据,但是NSFileManager在尝试执行moveItemAtURL时会抱怨相同的URL。

enter image description here


这里有两件事要知道:

  • 在iOS 9中,默认情况下不支持http://。 您必须安全通信(与https://进行通信)。 您可以根据需要在Info.plist中关闭此功能。

  • NSFileManager URL必须是磁盘上文件的路径-即,它们必须是文件URL。 你不是 这是一个http:// URL。 如果您的目标是下载文件然后将其复制到某处,请使用NSURLSession的下载任务。