https://github.com/potato512/SYSwiftLearning
效果图
关键代码
var cameraPicker:UIImagePickerController! = nil
// MARK: 摄像 func videoShow() { /* 使用如下属性时,注意添加framework:MobileCoreServices KUTTypeImage 包含 const CFStringRef kUTTypeImage ;抽象的图片类型 const CFStringRef kUTTypeJPEG ; const CFStringRef kUTTypeJPEG2000 ; const CFStringRef kUTTypeTIFF ; const CFStringRef kUTTypePICT ; const CFStringRef kUTTypeGIF ; const CFStringRef kUTTypePNG ; const CFStringRef kUTTypeQuickTimeImage ; const CFStringRef kUTTypeAppleICNS const CFStringRef kUTTypeBMP; const CFStringRef kUTTypeICO; KUTTypeMovie 包含: const CFStringRef kUTTypeAudiovisualContent ;抽象的声音视频 const CFStringRef kUTTypeMovie ;抽象的媒体格式(声音和视频) const CFStringRef kUTTypeVideo ;只有视频没有声音 const CFStringRef kUTTypeAudio ;只有声音没有视频 const CFStringRef kUTTypeQuickTimeMovie ; const CFStringRef kUTTypeMPEG ; const CFStringRef kUTTypeMPEG4 ; const CFStringRef kUTTypeMP3 ; const CFStringRef kUTTypeMPEG4Audio ; const CFStringRef kUTTypeAppleProtectedMPEG4Audio; */ // 获得相机模式下支持的媒体类型 let availableMediaTypes:Array = UIImagePickerController.availableMediaTypesForSourceType(.Camera)! var canTakeVideo = false for mediaType in availableMediaTypes { if mediaType == (kUTTypeImage as String) { // 支持摄像 canTakeVideo = true break; } } // 检查是否支持摄像 if (!canTakeVideo) { print("sorry,capturing video is not supported.!!!"); return; } // 创建图像选取控制器 let videoPicker = UIImagePickerController() // 设置图像选取控制器的来源模式为相机模式 videoPicker.sourceType = UIImagePickerControllerSourceType.Camera // 设置图像选取控制器的类型为动态图像,即视频文件 videoPicker.mediaTypes = [kUTTypeMovie as String] // 设置摄像图像品质 videoPicker.videoQuality = UIImagePickerControllerQualityType.TypeHigh // 设置最长摄像时间 videoPicker.videoMaximumDuration = 30 // 允许用户进行编辑 videoPicker.allowsEditing = false // 设置委托对象 videoPicker.delegate = self // 以模式视图控制器的形式显示 self.presentViewController(videoPicker,animated: true,completion: nil) }
// MARK: UIImagePickerControllerDelegate,UINavigationControllerDelegate func imagePickerController(picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : AnyObject]) { print("1 图片选择:\(info)") // 录像 // 获取媒体类型 let mediaType = info[UIImagePickerControllerMediaType] as! String // 判断是静态图像还是视频 if mediaType == (kUTTypeImage as String) { } else if mediaType == (kUTTypeMovie as String) { // 获取视频文件的url let mediaURL = info[UIImagePickerControllerMediaURL] as! NSURL // 视频文件的地址 let pathString = mediaURL.relativePath print("视频地址:\(pathString)") // 创建ALAssetsLibrary对象并将视频保存到媒体库(注意添加frame:AssetsLibrary) let assetsLibrary = ALAssetsLibrary() assetsLibrary.writeVideoAtPathToSavedPhotosAlbum(mediaURL,completionBlock: { (assetURL:NSURL!,error:NSError!) -> Void in if let errorTmp = error { print("保存失败:\(errorTmp)"); } else { print("保存成功"); } }) } // 退出图片选择控制器 picker.dismissViewControllerAnimated(true,completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { print("2 放弃图片选择") // 退出图片选择控制器 picker.dismissViewControllerAnimated(true,completion: nil) }