swift獲取系統(tǒng)相冊

1.遵守協(xié)議

UIImagePickerControllerDelegate,UINavigationControllerDelegate
  • 方法, 拍照或者從系統(tǒng)相冊獲取
//MARK:拍照或相冊選擇
    func choicePhotoWithType(type: UIImagePickerControllerSourceType) {
        if UIImagePickerController.isSourceTypeAvailable(type) {
            let picker = UIImagePickerController.init()
            picker.delegate = self//代理
            picker.sourceType = type//來源
            picker.allowsEditing = true
            self.presentViewController(picker, animated: true, completion: nil)
        }else {
            let str: String?
            if type == UIImagePickerControllerSourceType.Camera {
                str = "攝像頭不可用"
            }else
            {
                str = "相冊不可用"
            }
            let alertController: UIAlertController = UIAlertController.init(title: "溫馨提示", message: str, preferredStyle: UIAlertControllerStyle.Alert)
            let action: UIAlertAction = UIAlertAction.init(title: "知道了", style: UIAlertActionStyle.Default, handler: { (action) in
                alertController.dismissViewControllerAnimated(true, completion: nil)
            })
            alertController.addAction(action)
            presentViewController(alertController, animated: true, completion: nil)
        }
    }

  • 保存照片
//保存圖片到本地
    func savePhotoToLibrary(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(PersionViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    
    func image(image: UIImage, didFinishSavingWithError: NSError?,contextInfo: AnyObject) {
        if didFinishSavingWithError != nil {
            print("\(didFinishSavingWithError)")
        }else
        {
            print("保存圖片成功")
        }
    }

  • 代理方法
// 選擇完畢后獲得照片
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        let image:UIImage = info["UIImagePickerControllerEditedImage"] as! UIImage
        // 拍照
        if picker.sourceType == UIImagePickerControllerSourceType.Camera {
            savePhotoToLibrary(info["UIImagePickerControllerOriginalImage"] as! UIImage)
        }
        headView.iconImageView.image = image
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }

效果圖 2
效果圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容