我尝试使用以下代码下载pdf文件。它存储在应用程序数据中。但是我需要在iPhone的 “文件” 文件夹中显示下载的pdf 。
// Create destination URL let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.jpg") //Create URL to the source file you want to download let fileURL = URL(string: "http://swift-lang.org/guides/tutorial.pdf") 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()
可能吗??
这是下载任何文件并保存到“照片”(如果是图像文件)或“文件”(如果是pdf)的方法
let urlString = "your file url" let url = URL(string: urlString) let fileName = String((url!.lastPathComponent)) as NSString // Create destination URL let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL! let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)") //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) do { //Show UIActivityViewController to save the downloaded file let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles) for indexx in 0..<contents.count { if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent { let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil) self.present(activityViewController, animated: true, completion: nil) } } } catch (let err) { print("error: \(err)") } } 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()