如何在App Extensions iOS中添加下载选项

时间:2018-08-09 05:51:31

标签: ios swift xcode download nsfilemanager

enter image description here

我在行动扩展中看到了一些带有下载选项的应用程序如何实现此目的 以便从URL下载pdf文件并将该文件存储在手机内存中

let urlString = "http://www.gadgetsaint.com/wp-content/uploads/2016/11/cropped-web_hi_res_512.png"

     var url = URL(string: urlString)

    let audioFileName = String((url!.lastPathComponent)) as NSString
    let pathExtension = audioFileName.pathExtension


    // Create destination URL
    let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
    let destinationFileUrl = documentsUrl.appendingPathComponent("pathExtension.jpg")

    //Create URL to the source file you want to download
    let fileURL = URL(string: urlString)

    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)

    let request = URLRequest(url:fileURL!)

    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("Successfully downloaded. Status code: \(statusCode)")
            }

            do {
                try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
            } catch (let writeError) {
                print("Error creating a file \(destinationFileUrl) : \(writeError)")
            }

        } else {
            print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
        }
    }
    task.resume()

我已设法使用此代码下载文件,但无法将文件存储在手机内存中,但数据仍在应用程序中,因此需要一种解决方案将下载的文件从应用程序数据移动到手机内存中

0 个答案:

没有答案