我需要检测网址中的视频。我知道如何直接从视频网址下载视频。但是,我需要下载视频间接网址。例如,我点击了任何youtube视频链接,然后我想检测直接视频网址并从此页面上的直接视频网址下载。 换句话说,如何在网页上找到“.mp4”扩展链接?这是我使用的代码,但只有当url以“.mp4”
结尾时才有效@IBAction func downloadButtonAction(_ sender: Any) {
let urlString = "https://example.com/sample.mp4"
downloadVideoLinkAndCreateAsset(urlString)
}
func downloadVideoLinkAndCreateAsset(_ videoLink: String) {
// use guard to make sure you have a valid url
guard let videoURL = URL(string: videoLink) else { return }
guard let documentsDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
// check if the file already exist at the destination folder if you don't want to download it twice
if !FileManager.default.fileExists(atPath: documentsDirectoryURL.appendingPathComponent(videoURL.lastPathComponent).path) {
// set up your download task
URLSession.shared.downloadTask(with: videoURL) { (location, response, error) -> Void in
// use guard to unwrap your optional url
guard let location = location else { return }
// create a deatination url with the server response suggested file name
let destinationURL = documentsDirectoryURL.appendingPathComponent(response?.suggestedFilename ?? videoURL.lastPathComponent)
do {
try FileManager.default.moveItem(at: location, to: destinationURL)
PHPhotoLibrary.requestAuthorization({ (authorizationStatus: PHAuthorizationStatus) -> Void in
// check if user authorized access photos for your app
if authorizationStatus == .authorized {
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: destinationURL)}) { completed, error in
if completed {
print("Video asset created")
} else {
print(error as Any)
}
}
}
})
} catch { print(error) }
}.resume()
} else {
print("File already exists at destination url")
}
}