首页 > 解决方案 > Swift:从 Internet 下载和保存自定义文件

问题描述

我希望我的应用程序从 Internet 下载具有自定义扩展名的文件并保存。我写了以下代码:

import UIKit
class ViewController: UIViewController {

let url_to_my_file: URL = (URL(string: "https://my-url.com/file1.tcr"))!

override func viewDidLoad() {
    super.viewDidLoad()

    Downloader.load(url: url_to_my_file) {
        print("done")
    }
  }
}

====

import Foundation

class Downloader {

static let instanse = Downloader()

class func load(url: URL, completion: @escaping () -> ()) {

    let documentsURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true).first!, isDirectory: true)
    let localUrl = documentsURL.appendingPathComponent("file.tcr")!

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    var request = try! URLRequest(url: url)
    request.httpMethod = "GET"

    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Success: \(statusCode)")
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: localUrl)
                completion()
            } catch (let writeError) {
                print("error writing file \(localUrl) : \(writeError)")
            }

        } else {
            print("Failure: %@", error?.localizedDescription);
        }
    }
    task.resume()
  }
}

但是,当我运行它时,我会在控制台中收到我的代码不符合 ATS 策略的消息。

2018-07-12 21:44:31.965978+0300 dl_test[5294:4397157] App Transport Security
has blocked a cleartext HTTP (http://) resource load since it is insecure.
Temporary exceptions can be configured via your app's Info.plist file.
2018-07-12 21:44:31.966028+0300 dl_test[5294:4397157] Cannot start load of Task
<52F90327-B8A3-436D-B68C-716EBACFF0BF>.<1> since it does not conform to ATS
policy
2018-07-12 21:44:31.966121+0300 dl_test[5294:4397159] Task <52F90327-B8A3-436D-
B68C-716EBACFF0BF>.<1> finished with error - code: -1022
Failure: %@ Optional("The resource could not be loaded because the App
Transport Security policy requires the use of a secure connection.")

奇怪的事情,如果我把let url_to_my_file: URL = (URL(string: "https://my-url.com/file2.txt"))!而不是let url_to_my_file: URL = (URL(string: "https://my-url.com/file1.tcr"))!,一切正常,文件被保存和下载。我尝试将 file1 的扩展名交换为 .txt,但它没有改变任何东西。

我相信为了遵守 ATS 政策,我需要做的就是确保我使用的是 HTTPS,而不是 HTTP 链接。某些数据类型是否还有其他特定要求,或者我在代码中是否犯了其他错误?

我想遵守该政策,而不使用诸如编辑之类的变通方法info.plist。有没有办法做到这一点?

ps 不幸的是,我的项目不允许使用 Alamofire 或任何其他 pod

pps 我知道这个主题Transport security has blocked a cleartext HTTP,但是响应者通过编辑 inof.plist 提供了解决方法,这不是我正在寻找的解决方案

标签: swifturldownloadnsurlsessionnsurlrequest

解决方案


推荐阅读