保存图片到相册的解决方法

2018-07-11  本文已影响0人  best_su

访问权限 两个 记得info.plist中添加

Privacy - Photo Library Additions Usage Description
Privacy - Photo Library Usage Description

//swift方法一: 使用系统的回调方法

    let image = UIImage()
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)

    func image(image: UIImage, didFinishSavingWithError: NSError?, contextInfo: AnyObject){

        if PHPhotoLibrary.authorizationStatus() == .notDetermined {
            PHPhotoLibrary.requestAuthorization({ (status) in
                if status == .authorized {
                    print("点同意")
                } else if status == .denied || status == .restricted{
                    print("点拒绝")
                }
            })
        } else {
            print("无权限")
            return
        }
        
        
        if didFinishSavingWithError != nil{
            print("保存失败")
        }else{
            print("保存成功")
        }
    }

注:selector(image(image:didFinishSavingWithError:contextInfo:)),这个方法是系统的方法,oc的方法如下图所示:


oc的方法.png

swift:方法二: 使用Photo库中的方法


    @objc private func demoBtnClick(){
          let image = UIImage()
          savePhoto(image: image)
    }

    private func savePhoto(image: UIImage){
        
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: image)
            
        }){ (isSuccess: Bool, error: Error?) in
            if isSuccess == true{
                print("保存成功!")
            }else{
               print("保存失败:", error!.localizedDescription)
            }
        }
    }

上一篇下一篇

猜你喜欢

热点阅读