iOS保存视频、图片到相册

保存图片

swift 4.0

	//MARK:- save image
    func WM_FUNC_saveImage(_ image:UIImage) -> Void {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
@objc func image(_ image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer) {
    if let error = error {
        // we got back an error!
        let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    } else {
        let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
        ac.addAction(UIAlertAction(title: "OK", style: .default))
        present(ac, animated: true)
    }
}

OC

 //image是要保存的图片
- (void) saveImage:(UIImage *)image{
    if (image) {
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(savedPhotoImage:didFinishSavingWithError:contextInfo:), nil);
    };
}
//保存完成后调用的方法
- (void) savedPhotoImage:(UIImage*)image didFinishSavingWithError: (NSError *)error contextInfo: (void *)contextInfo {
    if (error) {
        NSLog(@"save error%@", error.localizedDescription);
    }
    else {
        NSLog(@"save success");
    }
}

保存视频

swift4.0

 //MARK:- save video
    func WM_FUNC_saveVideo(_ urlStr:String) -> Void {
        UISaveVideoAtPathToSavedPhotosAlbum(urlStr, self, #selector(videoSaveStatus(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    @objc func videoSaveStatus(_ urlstr: String, didFinishSavingWithError error: NSError?, contextInfo: UnsafeRawPointer){
       if error != nil {
       //error
       }else{
       //success
       }
    }

OC

//videoPath为视频下载到本地之后的本地路径 URL.path
- (void)saveVideo:(NSString *)videoPath{
    if (_videoPath) {
            if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum([_videoPath path])) {
                //保存相册核心代码
                UISaveVideoAtPathToSavedPhotosAlbum([_videoPath path], self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
            }
    }
}
//保存视频完成之后的回调
- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"save error%@", error.localizedDescription);
    }
    else {
        NSLog(@"save success");
    }
}

注: urlstr 如果是URL 使用 url.path 才能保存,还有就是要给相册权限

发布了121 篇原创文章 · 获赞 54 · 访问量 44万+

猜你喜欢

转载自blog.csdn.net/wm9028/article/details/103185519