首页 > 解决方案 > 从 Swift 5 FileManager 特定目标 URL 读取数据

问题描述

使用此代码下载代码后,我需要有人支持从 swift 5 FileManager 获取数据。

func downloadAction(destinationFile: String, FileUrlString: String){
    // Create destination URL
    let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
    print(documentsUrl)
       let destinationFileUrl = documentsUrl.appendingPathComponent(destinationFile)

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

       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()

     }

事实上,我尝试加载一些链接并成功完成,HTTP 状态代码为 200,但是!当我列出所有文件管理器项目时它没有出现。

let fm = FileManager.default
    let path = Bundle.main.resourcePath!
    let items = try! fm.contentsOfDirectory(atPath: path)

    for item in items {
        print(item)
    }

任何人都可以帮助查找文件以及如何在我的代码中使用它

谢谢你

标签: swiftdownloadswift5urlfetch

解决方案


那是我用来下载、播放和删除视频的代码。

  //MARK: Save Video   
func saveVideo(title:String,url:URL,didSuccess:@escaping ((Bool)->())) {

    ad.isLoading()
    DispatchQueue.global(qos: .userInitiated).async {
        guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
            DispatchQueue.main.async {
                ad.killLoading()
                didSuccess(false)
                
            }
            return }
        if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(url.lastPathComponent).path) {
            URLSession.shared.downloadTask(with: url) { (location, response, error) -> Void in
                guard let location = location else {
                    DispatchQueue.main.async {
                        ad.killLoading()
                        didSuccess(false)
                        
                    }
                    return }
                let destinationURL = documentsDirectoryURL.appendingPathComponent(url.lastPathComponent)
                
                do {
                    try FileManager.default.moveItem(at: location, to: destinationURL)
                    PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in
                        if authorizationStatus == .authorized {
                            PHPhotoLibrary.shared().performChanges({
                                PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
                                    DispatchQueue.main.async {
                                        if completed {
                                            //                                                    self.view.makeToast(NSLocalizedString("Video Saved!", comment: "Video Saved!"), duration: 3.0, position: .center)
                                            DispatchQueue.main.async {
                                                ad.killLoading()
                                                didSuccess(true)
                                                
                                            }
                            
                                            print("DID Save Video \(destinationURL)")
                                            //MARK: IF you want to check the video is working 
    /*
                                            let player = AVPlayer(url: destinationURL)  // video path coming from above function
                                            
                                            let playerViewController = AVPlayerViewController()
                                            playerViewController.player = player
                                            self.present(playerViewController, animated: true) {
                                                playerViewController.player!.play()
                                            }
                                      */      
                                            
                                        } else {
                                            print("Failed in Saveing Video")
                                            DispatchQueue.main.async {
                                                ad.killLoading()
                                                didSuccess(false)
                                            }
                                            print(error)
                                        }
                                    }
                            }
                        }
                    })
                } catch {
                    DispatchQueue.main.async {
                        ad.killLoading()
                        didSuccess(false)
                        
                    }
                    print(error) }
                
            }.resume()
        } else {
            print("File already exists at destination url")
            DispatchQueue.main.async {
                ad.killLoading()
                didSuccess(true)
                
            }
        }
    }
    
    
}





    
//MARK: Check if video exist
func checkIfVideoExist(url:URL) -> Bool {
    guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return false }
    
    return FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(url.lastPathComponent).path)
    
    
}

//MARK: PlayVideoFrom Url 
func playVideoFrom(url:URL) -> Bool {
    guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return false    }
    guard checkIfVideoExist(url: url) else { return false }
    let destinationURL = URL(fileURLWithPath:documentsDirectoryURL.appendingPathComponent(url.lastPathComponent).path)
    print(destinationURL)
    let player = AVPlayer(url: destinationURL)  // video path coming from above function
    
    let playerViewController = AVPlayerViewController()
    playerViewController.player = player
    self.present(playerViewController, animated: true) {
        playerViewController.player!.play()
    }
    return true
}
//MARK: Delete Video
func deleteVideoFromLocalStorage(url:URL) -> Bool {
    guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return  false }
    let destinationURL = URL(fileURLWithPath:documentsDirectoryURL.appendingPathComponent(url.lastPathComponent).path)
    
    do {
        try FileManager.default.removeItem(at: destinationURL)
        return true
    }
    catch(let err) {
        print("FAILED DELETEING VIDEO DATA \(err.localizedDescription)")
        return false
    }
}

推荐阅读