Swift - How to Know When The File Is Successfully Download from Url Using Filemanager.Default.Copyitem

Reading Data from Swift 5 FileManager specific destination URL

That is the code I used to download,play and delete videos.

  //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
}
}

How to download file in swift?

Example downloader class without Alamofire:

class Downloader {
class func load(URL: NSURL) {
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = session.dataTaskWithRequest(request, completionHandler: { (data: NSData!, response: NSURLResponse!, error: NSError!) -> Void in
if (error == nil) {
// Success
let statusCode = (response as NSHTTPURLResponse).statusCode
println("Success: \(statusCode)")

// This is your file-variable:
// data
}
else {
// Failure
println("Failure: %@", error.localizedDescription);
}
})
task.resume()
}
}

This is how to use it in your own code:

class Foo {
func bar() {
if var URL = NSURL(string: "http://www.mywebsite.com/myfile.pdf") {
Downloader.load(URL)
}
}
}

Swift 3 Version

Also note to download large files on disk instead instead in memory. see `downloadTask:

class Downloader {
class func load(url: URL, to localUrl: URL, completion: @escaping () -> ()) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = try! URLRequest(url: url, method: .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()
}
}

Not getting eject file after unzipping downloaded file URL

Tried replacing the name of the file at the time of successfully download using below code. -->

 func saveFileInDocDirectory(data: Data?, fileName: String?, successblock: @escaping (_ path: String?) -> Void) { // To add the image to cache for given identifier.

let paths = NSSearchPathForDirectoriesInDomains( .documentDirectory, .userDomainMask, true)[0] as String
let path = paths.appending("/\(fileName!)")
if (FileManager.default.fileExists(atPath: path)) {
try! FileManager.default.removeItem(atPath: path)
} else {
do {
try data?.write(to: URL(fileURLWithPath: path, isDirectory: false))
successblock(path)
} catch {
successblock(nil)
print("Error while caching the data in cache folder.")
}
}

}

And after that unzipped using SSZipArchive library in Alamofire download function -->

Alamofire.download(fileURL!, method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers, to: destination).downloadProgress(closure: { (progress) in
print(progress.completedUnitCount)
}).responseData { (responce) in
let destiUrl = responce.destinationURL
print(destiUrl!)
let name = destiUrl?.deletingPathExtension().lastPathComponent
self.saveFileInDocDirectory(data: responce.result.value, fileName: "\(name!).zip", successblock: { (path) in
print(path!)
var filepath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
let url = URL(fileURLWithPath: filepath)
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
let done = SSZipArchive.unzipFile(atPath: path!, toDestination: url.path)
if done{
let items = try FileManager.default.contentsOfDirectory(atPath: url.path)
print(items)
let destinationUrl = url.appendingPathComponent(items[0])
print(destinationUrl)
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
player = AVQueuePlayer(url: destinationUrl)
player.play()
}
} catch let error as NSError{
print(error)
}
})

}


Related Topics



Leave a reply



Submit