[英]How to save a video from my app in to the users photo library in iOS?
我的 iOS 應用程序允許用戶拍照或錄制視頻,如果他們願意,可以將其發送並保存到他們的相冊中。 我已經完成了所有工作,但我不知道如何保存視頻。 我已經用谷歌搜索過了,但我看到的大部分代碼似乎已經過時了。 我已經嘗試了以下代碼,但 Xcode 給了我錯誤,例如“在范圍中找不到‘UTTypeCopyPreferredTagWithClass’”等(我已經導入了 UniformTypeIdentifiers)。 我也不太確定這段代碼是否真的有任何作用。
// Write video to disk
guard let fileExtension = UTTypeCopyPreferredTagWithClass(photoEditViewController.configuration.photoEditViewControllerOptions.outputImageFileFormatUTI, kUTTagClassFilenameExtension)?.takeRetainedValue() as String?,
let filename = (ProcessInfo.processInfo.globallyUniqueString as NSString).appendingPathExtension(fileExtension) else {
return
}
let fileURL = URL(fileURLWithPath: (NSTemporaryDirectory() as NSString).appendingPathComponent(filename))
try? data.write(to: fileURL, options: [.atomic])
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromImage(atFileURL: fileURL)
}) { _, _ in
// Delete video from disk
_ = try? FileManager.default.removeItem(at: fileURL)
}
這段代碼可以改進嗎,或者有什么更好的方法可以用來將視頻保存到 iOS 的照片庫?
嘗試使用它在照片庫中保存視頻,請參閱將視頻保存到相機膠卷
func requestAuthorization(completion: @escaping ()->Void) {
if PHPhotoLibrary.authorizationStatus() == .notDetermined {
PHPhotoLibrary.requestAuthorization { (status) in
DispatchQueue.main.async {
completion()
}
}
} else if PHPhotoLibrary.authorizationStatus() == .authorized{
completion()
}
}
func saveVideoToAlbum(_ outputURL: URL, _ completion: ((Error?) -> Void)?) {
requestAuthorization {
PHPhotoLibrary.shared().performChanges({
let request = PHAssetCreationRequest.forAsset()
request.addResource(with: .video, fileURL: outputURL, options: nil)
}) { (result, error) in
DispatchQueue.main.async {
if let error = error {
print(error.localizedDescription)
} else {
print("Saved successfully")
}
completion?(error)
}
}
}
}
功能使用:
self.saveVideoToAlbum(/* pass your final url to save */) { (error) in
//Do what you want
}
您可以使用UISaveVideoAtPathToSavePhotosAlbum
將視頻保存到圖庫
該函數將視頻添加到用戶相機相冊指定路徑中。
func UISaveVideoAtPathToSavedPhotosAlbum(_ videoPath: String,
_ completionTarget: Any?,
_ completionSelector: Selector?,
_ contextInfo: UnsafeMutableRawPointer?)
在 VideoPath 中,插入要保存的視頻的路徑。
另外可以先用函數UIVideoAtPathCompatibleWithSavedPhotosAlbum(_:)
檢查未保存的錯誤,看看視頻是否可以存入圖庫。
有關更多信息,請參閱蘋果開發者網站。
提供的兩個答案都很好。 我選擇 Hailey's 作為“正確”的,因為它非常適合簡單地保存視頻。 對於將來遇到此帖子的任何人。 您可以根據需要使用任何一種。 Schaheer 的代碼處理請求許可和保存視頻,如果您有路徑,Hailey 的代碼只會保存視頻。 我將上述兩個答案結合起來,並將其與另一個來源提供的示例代碼一起使用。
對於使用 IMGLY 照片或視頻編輯器 SDK 的其他人,我將很快發布我使用的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.