我想知道以下功能何时完成下载数据。
我知道我可以使用完成处理程序,但这是在NSObject中我想知道何时返回此函数的完成处理程序,确保视频已完全下载并准备就绪,在函数之前返回完成处理程序,我的View Controller恢复它的逻辑。
谢谢:)
func downloadVideo(identity:JSON_Video){
// use guard to make sure you have a valid url
let videoId = identity.video_id!
let videoString:String = "\(Constants.endPoint_video)\(videoId).mp4"
guard let videoURL = URL(string: videoString) else { return }
let library_url = self.findVideo(video: identity)
if self.findVideo(video: identity) != nil{
print("Video exists. No need to download")
print("Existing video \(library_url!)")
}else{
print("Video not found. Downloading now")
// Variables to input on request
let loginString = Constants.loginString
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// URL request
var urlRequest = URLRequest(url: videoURL)
urlRequest.httpMethod = "GET"
urlRequest.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
// do stuff with response, data & error here
if let error = error{
print("Data Session Error: \(error.localizedDescription)")
print(response ?? "No response")
return
}
if let data = data {
print("Incoming video....")
print("Data: \(data.description)")
if let finalDatabaseURL = self.videosBaseUrl()?.appendingPathComponent("\(identity.video_id!).mp4"){
print("Copying from: \(videoURL)")
print("Copying to: \(finalDatabaseURL)")
do {
try
data.write(to: finalDatabaseURL)
print("Writing data to file")
// *****
// How do I know when data finished writing?
// Completion handler goes here ?
// *****
}catch{
print("Error writing data to file")
print(error.localizedDescription)
}
}
}
}
})
task.resume()
}
}