iOS9中,Swift判斷相機,相簿許可權,選取圖片為頭像

來源:互聯網
上載者:User

在iOS7以後要開啟手機網路攝影機或者相簿的話都需要許可權,在iOS9中更是更新了相簿相關api的調用

首先建立一個swift工程,在SB中放上一個按鈕,並在viewController中拖出點擊事件

ok!按鈕和事件設定好以後,我們來引入要用到的庫,判斷網路攝影機許可權,需要引入AVFoundation.framework,搜尋並進行添加

在ViewController中 import AVFoundation

並遵循以下幾個代理UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate

聲明我們需要的變數

    var img :UIImageView!
    var sheet:UIAlertController!

    var sourceType = UIImagePickerControllerSourceType.PhotoLibrary //將sourceType賦一個初實值型別,防止調用時不賦值出現崩潰

在viewDidLoad中:

override func viewDidLoad() {
        super.viewDidLoad()
        img = UIImageView(frame: CGRectMake(20, 120, 100, 100))
        self.view.addSubview(img)
       
    }

由於我們選擇相簿或者開啟網路攝影機以後進行圖片編輯的操作是一樣的,所以我們將這段代碼封裝到open方法裡面

//    開啟圖庫或相機
    func open(){
        
        let imagePickerController:UIImagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.allowsEditing = true//true為拍照、選擇完進入圖片編輯模式
        imagePickerController.sourceType = sourceType
        self.presentViewController(imagePickerController, animated: true, completion:{
            
        })
 
  }

然後我們再將判斷相簿許可權和網路攝影機許可權的代碼封裝到各自的方法中進行調用

/**
     判斷相機許可權
     
     - returns: 有許可權返回true,沒許可權返回false
     */
    func cameraPermissions() -> Bool{
        
        let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
        
        if(authStatus == AVAuthorizationStatus.Denied || authStatus == AVAuthorizationStatus.Restricted) {
            return false
        }else {
            return true
        }
        
    }
(相機許可權的判斷和OC基本一致,只是方法調用方法變化了而已)

    /**
     判斷相簿許可權
     
     - returns: 有許可權返回ture, 沒許可權返回false
     */
    
    func PhotoLibraryPermissions() -> Bool {
        
        let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()
        if(library == PHAuthorizationStatus.Denied || library == PHAuthorizationStatus.Restricted){
            return false
        }else {
            return true
        }
    }

(相簿許可權判斷這裡在iOS9之前都是用的AssetsLibrary庫,在iOS9之後引用的是Photos庫了,雖然依然可以調用AssetsLibrary庫進行判斷,但會有警告Photos庫的引用,import Photos就行)

接下來就是在前面拖出的按鈕事件中進行代碼編寫了:


@IBAction func picker(sender: AnyObject) {
        
        //判斷設定是否支援圖片庫和相機
        if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) && UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary)){
        
            sheet = UIAlertController(title: nil, message: "選擇擷取頭像方式", preferredStyle: .ActionSheet)
        
            //取消
            let cancelAction = UIAlertAction(title: "取消", style: .Cancel, handler: {(action) in
                print("取消")
            })
            sheet.addAction(cancelAction)
            
            
            //相簿
            let OKAction = UIAlertAction(title: "相簿", style: .Default, handler: {(action) in
                if(self.PhotoLibraryPermissions() == true){
                    self.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
                    self.open()
                }else{
                    //彈出提示框
                    self.sheet = UIAlertController(title: nil, message: "請在設定中開啟相簿許可權", preferredStyle: .Alert)
                    
                    let tempAction = UIAlertAction(title: "確定", style: .Cancel) { (action) in
                        print("取消")
                        
                    }
                    self.sheet.addAction(tempAction)
                    self.presentViewController(self.sheet, animated: true, completion: nil)
                }
            })
            sheet.addAction(OKAction)
            
        
            //網路攝影機
            let destroyAction = UIAlertAction(title: "網路攝影機", style: .Default, handler: { (action) in
                if(self.cameraPermissions() == true){
                    self.sourceType = UIImagePickerControllerSourceType.Camera
                    self.open()
                }else {
                    //彈出提示框
                    self.sheet = UIAlertController(title: nil, message: "請在設定中開啟網路攝影機許可權", preferredStyle: .Alert)

                    let tempAction = UIAlertAction(title: "確定", style: .Cancel) { (action) in
                    }
                    self.sheet.addAction(tempAction)
                    self.presentViewController(self.sheet, animated: true, completion: nil)
                }
            })
            sheet.addAction(destroyAction)
            
        }
        
            self.presentViewController(self.sheet, animated: true, completion: nil)
}


最後


//    取消圖片選擇操作
    func imagePickerControllerDidCancel(picker:UIImagePickerController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    
//    選擇完圖片操作
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        img.image = image
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }

註:因前面判斷了相機判斷,demo只能在真機上運行

附上demo連結:點擊開啟連結

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.