• // ...// demo.swift // 相机demo // // Created by CmyLove on 16/5/3. // Copyright © 2016年 张金良. All rights reserved. // import Foundation import UIKit class Enterp

    //

    //  demo.swift

    //  相机demo

    //

    //  Created by CmyLove on 16/5/3.

    //  Copyright ©All rights reserved.

    //



    import Foundation

    import UIKit

    class EnterpriseRegistrationViewController:UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {

        override func viewDidLoad() {

            super.viewDidLoad()

            addViews()

        }

        func addViews(){

            self.view .backgroundColor=UIColor .greenColor()

            let btn = UIButton(frame: CGRectMake(30,80,50,50))

            btn.setTitle("相册", forState:UIControlState.Normal)

            btn.backgroundColor=UIColor .redColor()

            btn.addTarget(self, action:"demoClicked", forControlEvents: UIControlEvents.TouchUpInside)

            self.view .addSubview(btn)

            

          

            let btn1 = UIButton(frame: CGRectMake(90,80,50,50))

            btn1.setTitle("相机", forState:UIControlState.Normal)

            btn1.backgroundColor=UIColor .redColor()

            btn1.addTarget(self, action:"demoCameera", forControlEvents: UIControlEvents.TouchUpInside)

            self.view .addSubview(btn1)

            

        }

        func demoCameera(){

            openCamera()

            

        }

        func demoClicked(){

            openAlbum()

        }

        //打开相册

        func openAlbum(){

            //判断设置是否支持图片库

            ifUIImagePickerController.isSourceTypeAvailable(.PhotoLibrary){

                //初始化图片控制器

                let picker = UIImagePickerController()

                //设置代理

                picker.delegate = self

                //指定图片控制器类型

                picker.sourceType =UIImagePickerControllerSourceType.PhotoLibrary

                //设置是否允许编辑

                //            picker.allowsEditing = editSwitch.on

                //弹出控制器,显示界面

                self.presentViewController(picker, animated:true, completion: {

                    () -> Void in

                })

            }else{

                print("读取相册错误")

            }

        }

        

        func openCamera(){

            ifUIImagePickerController.isSourceTypeAvailable(.Camera){

                

                //创建图片控制器

                let picker = UIImagePickerController()

                //设置代理

                picker.delegate = self

                //设置来源

                picker.sourceType =UIImagePickerControllerSourceType.Camera

                //允许编辑

                picker.allowsEditing = true

                //打开相机

                self.presentViewController(picker, animated:true, completion: { () -> Void in

                    

                })

            }else{

                debugPrint("找不到相机")

            }

        }

        

        //选择图片成功后代理

        func imagePickerController(picker: UIImagePickerController,

            didFinishPickingMediaWithInfo info: [String :AnyObject]) {

                //查看info对象

                print(info)

                //获取选择的原图

                let image = info[UIImagePickerControllerOriginalImage]as! UIImage

                //            imageView.image = image

                //图片控制器退出

                picker.dismissViewControllerAnimated(true, completion: {

                    () -> Void in

                })

        }   

    }

    展开全文
  • Privacy - Camera Usage Description//访问相机 Privacy - Photo Library Usage Description//访问相册2.代码 //遵守两个协议 class DataViewController: UIViewController,UIImagePickerControllerDelegate,U

    1.准备工作

    在info.list
    Privacy - Camera Usage Description//访问相机
    Privacy - Photo Library Usage Description//访问相册
    Localized resources can be mixed 设为YES //显示系统文字(要不然为英文)

    2.代码

    
    //遵守两个协议
    class DataViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
     ///相机,相册
    var cameraPicker: UIImagePickerController!
    var photoPicker: UIImagePickerController!
    
      override func viewDidLoad() {
            super.viewDidLoad()
            self.initPhotoPicker()
            self.initCameraPicker()
        }
     //MARK: - Method
        func initCameraPicker(){
            cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.sourceType = .camera
            //在需要的地方present出来
            //self.present(cameraPicker, animated: true, completion: nil)
        }
    
        func initPhotoPicker(){
            photoPicker =  UIImagePickerController()
            photoPicker.delegate = self
            photoPicker.sourceType = .photoLibrary
            //在需要的地方present出来
            //self.present(photoPicker, animated: true, completion: nil)
        }
    
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
            self.dismiss(animated: true, completion: nil)
            //获得照片
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            if photoArray.count < 6 {
               photoArray.insert(image, at: 0)
            }else {
                //最多上传6张
            }
         }
    }

    3.相册的多选

    参考:https://github.com/apptut/PhotoPicker

    展开全文
  • AppDelegate中的方法 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -&gt; Bool { //MARK: APP启动时候,判断...

    AppDelegate中的方法

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
            //MARK: APP启动时候,判断用户是否授权使用相机
            if (AVCaptureDevice.authorizationStatus(for: AVMediaType.video) == .notDetermined) {
                AVCaptureDevice.requestAccess(for: .video, completionHandler: { (statusFirst) in
                    if statusFirst {
                        //用户首次允许
                        print("允许APP访问相机")
                    } else {
                        //用户首次拒接
                        print("拒绝APP访问相机")
                    }
                })
            }
           
            //MARK: APP启动时候,判断用户是否授权使用相册
            if (PHPhotoLibrary.authorizationStatus() == .notDetermined) {
                PHPhotoLibrary.requestAuthorization({ (firstStatus) in
                    let result = (firstStatus == .authorized)
                    if result {
                        print("允许APP访问相册")
                    } else {
                        print("拒绝APP访问相册")
                    }
                })
            }
            
            return true
        }
    

    相机、相册权限判断

    /****************************APP权限**************************************/
    /* .restricted     ---> 受限制,系统原因,无法访问
     * .notDetermined  ---> 系统还未知是否访问,第一次开启时
     * .authorized     ---> 允许、已授权
     * .denied         ---> 受限制,系统原因,无法访问
     */
    //MARK: 判断是否可访问相册
    //UIDevice.current.systemVersion >= 8.0
    ///相册权限---> 直接使用 <Photo方法 @available(iOS 8.0, *)>
    func photoEnable() -> Bool {
        func photoResult() {
            let status = PHPhotoLibrary.authorizationStatus()
            if (status == .authorized) {
                savePhoto(value: "1")
            }
            else if (status == .restricted || status == .denied) {
                let alertV = UIAlertView.init(title: "提示", message: "请去-> [设置 - 隐私 - 相册] 打开访问开关", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "确定")
                alertV.show()
                savePhoto(value: "0")
            }
            else if (status == .notDetermined) {//首次使用
                PHPhotoLibrary.requestAuthorization({ (firstStatus) in
                    let isTrue = (firstStatus == .authorized)
                    if isTrue {
                        print("首次允许")
                        savePhoto(value: "1")
                    } else {
                        print("首次不允许")
                        savePhoto(value: "0")
                    }
                })
            }
        }
        func savePhoto(value: String) {
            UserDefaults.standard.setValue(value, forKey: "photoEnablebs")
        }
        let result = (UserDefaults.standard.object(forKey: "photoEnablebs") as! String) == "1"
        return result
    }
    
    ///相册权限 --> 需要AppleDelegate中让用户先选择授权
    func photoEnableDelegate() -> Bool {
        let status = PHPhotoLibrary.authorizationStatus()
        if status == .authorized {
            return true
        }
        return false
    }
    
    //UIDevice.current.systemVersion < 8.0
    //depressed
    ///相册权限---> 需要AppleDelegate中让用户先选择授权, 此方法将被废弃 <AssetsLibrary方法 @available(iOS 7.0, *)>
    func photoEnableDelegate2() -> Bool {
        let author = ALAssetsLibrary.authorizationStatus()
        print("--\(author.rawValue)--")
        if (author == .restricted || author == .denied) {
            let alertV = UIAlertView.init(title: "提示", message: "请去-> [设置 - 隐私 - 相册] 打开访问开关", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "确定")
            alertV.show()
            return false
        }
        return true
    }
    
    //MARK: 判断是否可访问相机
    ///相机权限 ---> 直接调用
    func cameraEnable() -> Bool {
        func cameraResult() {
            let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
            
            if (authStatus == .authorized) { /****已授权,可以打开相机****/
                saveCamera(value: "1")
            }
                
            else if (authStatus == .denied) {
                saveCamera(value: "0")
                let alertV = UIAlertView.init(title: "提示", message: "请去-> [设置 - 隐私 - 相机] 打开访问开关", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "确定")
                alertV.show()
            }
                
            else if (authStatus == .restricted) {//相机权限受限
                saveCamera(value: "0")
                let alertV = UIAlertView.init(title: "提示", message: "相机权限受限", delegate: nil, cancelButtonTitle: nil, otherButtonTitles: "确定")
                alertV.show()
            }
                
            else if (authStatus == .notDetermined) {//首次 使用
                AVCaptureDevice.requestAccess(for: .video, completionHandler: { (statusFirst) in
                    if statusFirst {
                        //用户首次允许
                        saveCamera(value: "1")
                    } else {
                        //用户首次拒接
                        saveCamera(value: "0")
                    }
                })
            }
        }
        func saveCamera(value: String) {
            UserDefaults.standard.setValue(value, forKey: "cameraEnablebs")
        }
        cameraResult()
        let result = (UserDefaults.standard.value(forKey: "cameraEnablebs") as! String) == "1"
        return result
    }
    
    ///相机权限2 --> 需要AppleDelegate中让用户先选择授权
    func cameraEnableDelegate() -> Bool {
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if status == .authorized {
            return true
        }
        return false
    }
    
    /******************************************************************/

     

    展开全文
  • 打开相册相机 */ import UIKit import AVFoundation import Photos import MobileCoreServices class LYBOpenAblumOrCameraVC: UIViewController,UIImagePickerControllerDelegate,...
    /**
     打开相册或相机
     */
    import UIKit
    import AVFoundation
    import Photos
    import MobileCoreServices
    
    class LYBOpenAblumOrCameraVC: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
        var  pickImageController:UIImagePickerController?
        override func viewDidLoad() {
            super.viewDidLoad()
            
           selectPhotoOrCamera(index: 0)
           
        }
        //选择相册、拍照、录像
        func selectPhotoOrCamera(index:Int){
            switch index {
            case 0://相册
                openAblum()
                break
                case 1://拍照
                openCamera(index: 1)
                break
                   case 2://录像
                openCamera(index: 2)
                break
            default: break
                
            }
        }
          //打开相册
        func openAblum(){
            weak var weakSelf=self
    
             pickImageController=UIImagePickerController.init()
            //savedPhotosAlbum是根据日期排列,photoLibrary是所有相册
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.photoLibrary){
                
                //获取相册权限
                PHPhotoLibrary.requestAuthorization({ (status) in
                    switch status {
                    case .notDetermined: break
                    
                    case .restricted://此应用程序没有被授权访问的照片数据
                        break
                    case .denied://用户已经明确否认了这一照片数据的应用程序访问
                        break
                    case .authorized://已经有权限
                        weakSelf!.pickImageController!.delegate=self
                        weakSelf!.pickImageController!.allowsEditing = true
                        weakSelf!.pickImageController!.sourceType = UIImagePickerController.SourceType.photoLibrary;
    //                    weakSelf?.pickImageController?.mediaTypes=[kUTTypeMovie as String]//只有视频
    //                 weakSelf?.pickImageController?.mediaTypes=[kUTTypeImage as String]//只有照片
            weakSelf?.pickImageController?.mediaTypes=UIImagePickerController.availableMediaTypes(for: UIImagePickerController.SourceType.photoLibrary)!//包括照片和视频
                        //弹出相册页面或相机
                        self.present( weakSelf!.pickImageController!, animated: true, completion: {
                        })
                        
                        break
                    }
                })
                
            }
            
    
        }
         //打开相机拍照或者录像
        func openCamera(index:Int){
            weak var weakSelf=self
     pickImageController=UIImagePickerController.init()
            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera){
                
                AVCaptureDevice.requestAccess(for: AVMediaType.video, completionHandler: { (ist) in
                    //检查相机权限
                    let status:AVAuthorizationStatus=AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
                    if status==AVAuthorizationStatus.authorized {// 有相机权限
                        
                        //跳转到相机或者相册
                        weakSelf!.pickImageController!.delegate=self
                            weakSelf!.pickImageController!.allowsEditing = true
                        self.pickImageController!.sourceType = UIImagePickerController.SourceType.camera;
    
                        if index==1{//拍照
                            weakSelf?.pickImageController?.mediaTypes=[kUTTypeImage as String]//拍照
                            
                        }else if index==2{
                    weakSelf?.pickImageController?.mediaTypes=[kUTTypeMovie as String]//录像
                        }else {
        weakSelf?.pickImageController?.mediaTypes=UIImagePickerController.availableMediaTypes(for: UIImagePickerController.SourceType.photoLibrary)!//拍照和录像都可以
                        }
                        //弹出相册页面或相机
                        self.present(self.pickImageController!, animated: true, completion: {
                            
                        })
                    }else if (status==AVAuthorizationStatus.denied)||(status==AVAuthorizationStatus.restricted) {
                        
                    }else if(status==AVAuthorizationStatus.notDetermined){//权限没有被允许
                        //去请求权限
                        AVCaptureDevice.requestAccess(for: AVMediaType.video) { (genter) in
                            if (genter){
                                print("去打开相机")
                            }else{
                                print(">>>访问受限")
                            }
                        }
                    }
                })
            }
        }
        //去设置权限
        @available(iOS 10.0, *)
        func gotoSetting(){
            let alertController:UIAlertController=UIAlertController.init(title: "去设置", message: "设置-》通用-》", preferredStyle: UIAlertController.Style.alert)
            
            let sure:UIAlertAction=UIAlertAction.init(title: "去开启权限", style: UIAlertAction.Style.default) { (ac) in
                let url=URL.init(string: UIApplication.openSettingsURLString)
                if UIApplication.shared.canOpenURL(url!){
                  
                        UIApplication.shared.open(url!, options: [:], completionHandler: { (ist) in
                            
                  
                       UIApplication.shared.openURL(url!)
                 
                  })
                }
            }
            alertController.addAction(sure)
            self.present(alertController, animated: true) {
                
            }
        }
        
        //    要将MobileCoreServices 框架添加到项目中,导入:#import <MobileCoreServices/MobileCoreServices.h> 。不然后出现错误使用未声明的标识符 'kUTTypeMovie'
        //    swift 中import MobileCoreServices
        
        //选中图片,保存图片或视频到系统相册
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
       
            //取消选择
            picker.dismiss(animated: true) {
    
            }
            var image: UIImage?
            print("\(info)")
            /**
             info打印出来的值
             [__C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerMediaType): public.image, __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerCropRect): NSRect: {{0, 0}, {750, 558}}, __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerEditedImage): <UIImage: 0x281232ae0> size {750, 558} orientation 0 scale 1.000000, __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerOriginalImage): <UIImage: 0x28122dd50> size {750, 557} orientation 0 scale 1.000000, __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerPHAsset): <PHAsset: 0x14be77900> 25183429-BD2B-4C3B-A850-1161B45F21CB/L0/001 mediaType=1/4, sourceType=1, (750x557), creationDate=2018-12-19 06:57:17 +0000, location=0, hidden=0, favorite=0 , __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerReferenceURL): assets-library://asset/asset.JPG?id=25183429-BD2B-4C3B-A850-1161B45F21CB&ext=JPG, __C.UIImagePickerControllerInfoKey(_rawValue: UIImagePickerControllerImageURL): file:///private/var/mobile/Containers/Data/Application/9D23C5AB-8CA2-4BA1-ADFB-1CDF0251F9A4/tmp/9E4D6A79-8EA2-4EF4-96AA-B65E0F497B11.jpeg]
             */
            
            
            let typ:String = (info[UIImagePickerController.InfoKey.mediaType]as!String)//类型
            // 图片类型"public.image"
            if typ == "public.image"{
                if(picker.allowsEditing){
                    //裁剪后图片
                    image=(info[UIImagePickerController.InfoKey.editedImage] as! UIImage)
                }else{
                    //原始图片
                    image=(info[UIImagePickerController.InfoKey.originalImage] as! UIImage)
                }
                
                //缩小图片
                let newSize=CGSize.init(width: 100, height: 100)
                UIGraphicsBeginImageContext(newSize)
                
                image!.draw(in: CGRect.init(x: 0, y: 0, width: newSize.width, height: newSize.height))
                let newImage:UIImage=UIGraphicsGetImageFromCurrentImageContext()!
                UIGraphicsEndImageContext();
                //        这个是系统的方法,先来解释下各个参数:
                //        1.image:将要保存的图片
                //        2.completionTarget:保存完毕后,回调方法所在的对象
                //        3.completionSelector:保存完毕后,回调的方法
                //        4.contextInfo:可选参数
                UIImageWriteToSavedPhotosAlbum(newImage, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    
            }else if typ == "public.movie"{
                //视频类型
                let url = info[UIImagePickerController.InfoKey.mediaURL] as! NSURL//视频的url
                let urlStr = url.path
                if UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(urlStr!){
                //保存视频到相簿,
                    PHPhotoLibrary.shared().performChanges({
                        PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: URL(string:urlStr!)!)
                    }) { (boo, error) in
                        if boo{
                            print("保存视频成功")
                        }
                      
                    }
                }
              
    
        }
        
        }
        //保存到系统相册
        
        @objc func image(image:UIImage,didFinishSavingWithError error:NSError?,contextInfo:AnyObject) {
            print("保存相册成功")
        }
    }

     

    展开全文
  • swift --- 相册选择 和照相机
  • 拍照、访问相册 swift

    2019-03-13 14:11:26
    设置用户权限请求: 在Info.plist文件中添加Privacy - Camera Usage Description和Privacy - Photo Library Usage Description字段 设置代理: ...class BasicPhotoViewController: UIViewController, ...

    设置用户权限请求:

    在Info.plist文件中添加Privacy - Camera Usage Description和Privacy - Photo Library Usage Description字段

     

    设置代理:

    class BasicPhotoViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate

     

    代码实现:

    1. 让用户选择从相册上传照片或是拍照
                  let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
                  alert.addAction(UIAlertAction(title: "打开相机", style: .default, handler: { (alertCamera) in
                      let picker = UIImagePickerController()
                      picker.delegate = self
                      picker.sourceType = .camera
                      picker.allowsEditing = true
                      if UIImagePickerController.isSourceTypeAvailable(.camera) {
                          self.present(picker, animated: true, completion: nil)
                      } else {
                          self.showAwardInfo(info: "请打开相机权限")
                      }
                  }))
                  alert.addAction(UIAlertAction(title: "打开相册", style: .default, handler: { (alertAlbum) in
                      let picker = UIImagePickerController()
                      picker.delegate = self
                      picker.sourceType = .photoLibrary
                      picker.allowsEditing = true
                      if UIImagePickerController.isSourceTypeAvailable(.camera) {
                          self.present(picker, animated: true, completion: nil)
                      } else {
                          self.showAwardInfo(info: "请打开相册权限")
                      }
                  }))
                  alert.addAction(UIAlertAction(title: "取消", style: .cancel, handler: nil))
                  self.present(alert, animated: true, completion: nil)

       

    2. 实现代理方法
          func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
              if let choseImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
                  picker.dismiss(animated: true) {
                      //自定义对图片choseImage处理
                  }
              }
          }

       

     

    展开全文
  • swift调用相机相册

    2019-08-10 06:52:28
    简单实现swift调用相机相册的功能,分享代码与学习swift的童鞋共同进步 import UIKit class ViewController: UIViewController,UIImagePickerControllerDelegate,UINavigationControllerDelegate{ var...
  • // 相机权限 func isRightCamera() -&gt; Bool {  let authStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)  return authStatus != .restricted &amp;&amp; ...
  • iOS不同版本的自定义有所不同的,本文介绍iOS8下的自定义相机,所用语言为swift3+ // // TGCameraVCForiOS8.swift // TGPhotoPicker // // Created by targetcloud on 2017/8/11. // Copyright © 2017年 ...
  • 然后利用系统类UIImagePickerController调用相机相册,下面已经封装好了类,继承该类调用showImagePickerController()方法就会自动调用相机相册 github地址...
  • 在实际的项目中,我们经常会用到对相册进行操作的功能,在oc里,这类的框架挺多,也挺好,但是swift里实现这些功能的框架挺少,今天我们来介绍这么一个AlbumCore,完全用swift来实现。本项目来自已上线应用,源项目...
  • 最近要做一个iOS相机相册图片上传,其中遇到了这些问题:1、图片增删在UICollectionView里的变化;2、获取相机拍摄的照片和相册的照片;3、将PHAsset对象转为UIImage对象; 具体实现过程: 首先整个控件结构如图...
  • 一、创建项目 这个很简单,创建好了看下面的就行了 二、添加权限 拍照和获取相册都需要先设置权限 ...实现一个简单的布局,同一个界面,一个按钮 Button,一张图片 ImageView ...2、拍照或从相册选择...
  • Swift4 相机二维码扫描

    2019-02-28 02:25:44
    Swift4相机扫描二维码,复制粘贴拿走不谢
  • 对于iOS 中调用系统相册的功能,我想大家都比较熟悉了,但是Swift语言调用可能很多伙伴们不是很清楚,毕竟Swift是一门新语言,所以语法和实现方法可能不是很清楚,所以今天做了一个demo,大家可以做一下参考。...
  • iOS开发swift如何调用系统相册相机获取图片都是用UIImagePickerController  1.加上protocol UIImagePickerControllerDelegate,UINavigationControllerDelegate 2.打开系统相册相机的代码 ...
  • //点击按钮的方法 1 func photos() { 2 3 self.showBottomAlert() 4 5 } /// 屏幕底部弹出的Alert 1 func showBottomAlert(){ 2 3 let alertController=UIAlertController(t...
  • swift相机启动

    2017-12-12 07:53:46
    swift相机启动 swift相机启动问题
  • JS调用swift相册

    2017-03-24 05:09:51
    window.location.href = 'tg:///openCamera' ...在JS中用自己定义的协议头来协作JS和swift css body{ } img{ width:100%; } #mainTitle{ text-align:center; font-size:20px; margin-top:20px; margin-bott
1 2 3 4 5 ... 20
收藏数 1,032
精华内容 412
关键字:

4相册 swift 相机