在IOS开发中经常会用到系统相册,相机,音视频等功能。每次都写比较麻烦,自己封装了一个工具类,实现一句话调用系统相册,相机,音视频等功能。方便以后项目的开发。
//选择图片
[[OCSystemTool shareTool]choosePicture:self editor:YES finished:^(UIImage * _Nullable image) {
_headerView.image = image;
}];
//视频:http://baobab.wdjcdn.com/14562919706254.mp4
[[OCSystemTool shareTool]playVideoWithPath:@"apple.mp4" viewController:self];
//音乐
[[OCSystemTool shareTool]playAudioWithPath:@"song.mp3"];
//停止音乐播放
[[OCSystemTool shareTool]stopAudioPlayer];
本文附上OC版代码:(PS:Swift3.0版见链接www.jianshu.com/p/c8e99bf35970)
.h文字
//// Tool.h// SystemFunction//// Copyright (c) 2017年 hailong. All rights reserved.//#import#import#import#import@interface Tool : NSObject///<1>定义block
typedef void(^myBlock)(UIImage * _Nullable image);
///<2>声明属性
@property (nonatomic, copy) myBlock _Nullable block;
//音频播放器
@property (nonatomic, strong) AVAudioPlayer * _Nullable audioPlayer;
//带有视频播放器的控制器,能够播放MP4、MOV、avi、以及流媒体m3u8格式的视频,能够播放远程和本地的视频资源
@property (nonatomic, strong) AVPlayerViewController * _Nullable playerController;
@property (nonatomic, strong) AVPlayer *_Nullable videoPlayer;
//1 返回单例的静态方法
+(Tool *_Nullable)shareTool;
//2 选择图片
- (void)choosePicture:(UIViewController *_Nullable)controller editor:(BOOL)editor finished:(void (^_Nullable)(UIImage * _Nullable image))success;
//3 播放声音
- (void)playAudioWithPath:(NSString *_Nullable)sound;
//停掉音频
- (void)stopAudioPlayer;
///4 播放视频
-(void)playVideoWithPath:(NSString *_Nullable)videoPath viewController:(UIViewController*_Nullable)viewController;
//返回特定尺寸的UImage , image参数为原图片,size为要设定的图片大小
-(UIImage*_Nonnull)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage *_Nullable)image;
//在指定的视图内进行截屏操作,返回截屏后的图片
-(UIImage *_Nullable)imageWithScreenContentsInView:(UIView *_Nullable)view;
@end
.m文件
//// Tool.m// SystemFunction//// Copyright (c) 2017年 hailong. All rights reserved.//#import "Tool.h"#import//里面预置了跟系统设置资源相关的常量和一些参数#import@implementation Tool
static Tool *_shareTool =nil;
///1 返回单例的静态方法
+(Tool *)shareTool
{
//确保线程安全
@synchronized(self){
//确保只返回一个实例
if (_shareTool == nil) {
_shareTool = [[Tool alloc] init];
}
}
return _shareTool;
}
-(id)init
{
self = [super init];
if (self) {
}
return self;
}
///2 选择图片
- (void)choosePicture:(UIViewController *)controller editor:(BOOL)editor finished:(void (^)(UIImage * _Nullable image))success{
///<3>实现block
self.block = success;
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"请选择图片" message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
[alertC addAction:[UIAlertAction actionWithTitle:@"拍照" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//相机
[self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypeCamera controller:controller editor:editor];
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"从相册选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
//相册库
[self loadImagePickerWithSourceType:UIImagePickerControllerSourceTypePhotoLibrary controller:controller editor:editor];
}]];
[alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
}]];
[controller presentViewController:alertC animated:YES completion:nil];
}
///3 播放声音
- (void)playAudioWithPath:(NSString *_Nullable)audioPath{
//音频
NSURL *url;
//https 更安全的http协议
if ([audioPath rangeOfString:@"http://"].location != NSNotFound||[audioPath rangeOfString:@"https://"].location != NSNotFound) {
//远程的地址
url = [NSURL URLWithString:audioPath];
}else{
//本地的路径
NSString *localPath = [[NSBundle mainBundle] pathForResource:audioPath ofType:nil];
if (localPath.length==0) {
NSLog(@"没有读到资源!");
return;
}
url = [NSURL fileURLWithPath:localPath];
}
if (_audioPlayer) {
_audioPlayer = nil;
}
//AVPlayer
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
//设置代理
_audioPlayer.delegate = self;
[_audioPlayer prepareToPlay];//预处理
[_audioPlayer play];//播放
}
//停掉音频
- (void)stopAudioPlayer{
if (_audioPlayer) {
[_audioPlayer stop];//停止播放
_audioPlayer = nil;
}
}
///4 播放视频
-(void)playVideoWithPath:(NSString *)videoPath viewController:(UIViewController*)viewController{
NSURL *url;
//https 更安全的http协议
if ([videoPath rangeOfString:@"http://"].location !=NSNotFound||[videoPath rangeOfString:@"https://"].location!=NSNotFound) {
//远程的地址
url = [NSURL URLWithString:videoPath];
}else{
NSString *localPath = [[NSBundle mainBundle] pathForResource:videoPath ofType:nil];
if (localPath.length==0) {
NSLog(@"没有找到资源");
return;
}
url = [NSURL fileURLWithPath:localPath];
}
_playerController = [[AVPlayerViewController alloc]init];
_videoPlayer = [[AVPlayer alloc]initWithURL:url];
_playerController.player = _videoPlayer;
/*
可以设置的值及意义如下:
AVLayerVideoGravityResizeAspect 不进行比例缩放 以宽高中长的一边充满为基准
AVLayerVideoGravityResizeAspectFill 不进行比例缩放 以宽高中短的一边充满为基准
AVLayerVideoGravityResize 进行缩放充满屏幕
*/
_playerController.videoGravity = AVLayerVideoGravityResizeAspect;
[viewController presentViewController:_playerController animated:YES completion:^{
[self stopAudioPlayer];//停掉音频
//播放
[_playerController.player play];
}];
//NSNotificationCenter 通知中心,单例,可以理解为程序中的广播站
//在通知中心注册self成为某条广播的观察者(具有接收某条广播能力的一个对象)
//name 广播的名称
//作用:一旦有其他对象通过通知中心发送MPMoviePlayerPlaybackDidFinishNotification这条广播,self就能接收到,进而触发@selector方法
//涉及到对象一对多的场景(非常重要)
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
//通过通知中心发广播
//点击Done按钮,播放器会自动通过通知中心发送广播
//[[NSNotificationCenter defaultCenter] postNotificationName:MPMoviePlayerPlaybackDidFinishNotification object:nil];
}
- (void)playFinished{
//通过通知中心注销(移除)self对广播的观察
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
if (_playerController) {
[_playerController.player pause];
_playerController = nil;
}
}
#pragma mark - AVAudioPlayerDelegate
//一首歌播放完成后,调用此方法
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag{
NSLog(@"finshed!");
}
//当操作系统级别的功能介入(短信、电话),播放器被打断时,调用
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)player{
NSLog(@"begin interruption!");
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)player withOptions:(NSUInteger)flags{
if (player) {
[player play];//播放和继续播放
}
}
#pragma mark - 调用相机和相册库资源
- (void)loadImagePickerWithSourceType:(UIImagePickerControllerSourceType)type controller:(UIViewController *)controller editor:(BOOL)editor{
if (![UIImagePickerController isSourceTypeAvailable:type]){
[self showAlertWithMessage:@"相机无法使用" controller:controller];
return;
}
//UIImagePickerController 系统封装好的加载相机、相册库资源的类
UIImagePickerController *picker = [[UIImagePickerController alloc] init];
//加载不同的资源
picker.sourceType =type;
//是否允许picker对图片资源进行优化
picker.allowsEditing = editor;
picker.delegate = self;
//软件中习惯通过present的方式,呈现相册库
[controller presentViewController:picker animated:YES completion:^{
}];
}
- (void)showAlertWithMessage:(NSString *)message controller:(UIViewController *)controller {
UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
[alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
}]];
[controller presentViewController:alertC animated:YES completion:nil];
}
#pragma mark - 在指定的视图内进行截屏操作,返回截屏后的图片
-(UIImage *)imageWithScreenContentsInView:(UIView *)view
{
//根据屏幕大小,获取上下文
UIGraphicsBeginImageContext([[UIScreen mainScreen] bounds].size);
[view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return viewImage;
}
-(UIImage*)resizeImageToSize:(CGSize)size
sizeOfImage:(UIImage*)image
{
UIGraphicsBeginImageContext(size);
//获取上下文内容
CGContextRef ctx= UIGraphicsGetCurrentContext();
CGContextTranslateCTM(ctx, 0.0, size.height);
CGContextScaleCTM(ctx, 1.0, -1.0);
//重绘image
CGContextDrawImage(ctx,CGRectMake(0.0f, 0.0f, size.width, size.height), image.CGImage);
//根据指定的size大小得到新的image
UIImage* scaled= UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return scaled;
}
#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
//选择完照片 或者 照完相之后 ,会调用该方法,并且选择的图片或者照出来的图片都存到了info里面
/*
if (picker.sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
_headerView.image = image;
}else if (picker.sourceType == UIImagePickerControllerSourceTypeCamera){
UIImage *image =[info objectForKey:UIImagePickerControllerEditedImage];
_headerView.image = image;
}*/
//获取资源的类型(图片or视频)
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
//kUTTypeImage 代表图片资源类型
if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
//直接拿到选中的图片,
//手机拍出的照片大概在2M左右,拿到程序中对图片进行频繁处理之前,需要对图片进行转换,否则很容易内存超范围,程序被操作系统杀掉
UIImage *EditedImage = [info objectForKey:UIImagePickerControllerEditedImage];
UIImage *smallImage = [self resizeImageToSize:CGSizeMake(200,200) sizeOfImage:EditedImage];
///<4>调用block
self.block(smallImage);
}
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
//取消选择的图片
-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
[picker dismissViewControllerAnimated:YES completion:^{
}];
}
@end
/*
@interface ImageTool()
@end
*/