I am trying to save google drive videos in my photo gallery.
The code I am using:
@objc func saveVideosToPhone(videoURL:URL,viewController:UIViewController){
PHPhotoLibrary.requestAuthorization
{ (status) -> Void in
switch (status)
{
case .authorized:
// Permission Granted
print("Write your code here")
let urlData = NSData.init(contentsOf:videoURL)
if(urlData != nil)
{
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0];
let filePath = String.init(format:"\(documentsPath)/%@.mp4",self.randomString(length:5))
urlData?.write(toFile: filePath, atomically: true);
PHPhotoLibrary.shared().performChanges({
PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: NSURL(fileURLWithPath: filePath) as URL)
}) { completed, error in
if completed {
MBProgressHUD.hide(for:viewController.view, animated:false)
UtilityMethods.sharedInstance.showAlert(title:"Save", message:"Video is saved!", viewController:viewController)
print("Video is saved!")
}else{
MBProgressHUD.hide(for:viewController.view, animated:false)
UtilityMethods.sharedInstance.showAlert(title:"Error", message:(error?.localizedDescription)!, viewController:viewController)
print("error from gd",error?.localizedDescription)
}
}}
case .denied:
// Permission Denied
print("User denied")
default:
print("Restricted")
}
}
But,first time when the app asks for permission, and user gives permission, after that it shows the following error:
Photo access not allowed,authorization status 0
And, second time when user tries to save video to photo gallery ,it shows the following error:
The operation couldn't be completed