今天遇到一个需求,长按二维码保存到本地,现在就和大家分享下方法,(由于 iOS10的缘故 需要在 plist 文件里添加Privacy - Photo Library Usage Description字段)
#import "ViewController.h"
@interface ViewController ()
@property (nonatomic , strong)UIAlertView *myAlertView;
@property (nonatomic , strong)UIAlertView *myAlertView2;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
imageView.image = [UIImage imageNamed:@"User_load.jpg"];
imageView.tag = 10001;
imageView.userInteractionEnabled = YES;
[self.view addSubview:imageView];
//长按
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPassAction:)];
[imageView addGestureRecognizer:longPress];
//判定为长按手势 需要的时间
longPress.minimumPressDuration = 1;
//判定时间,允许用户移动的距离
longPress.allowableMovement = 100;
}
//长按手势
- (void)longPassAction:(UILongPressGestureRecognizer *)longPress{
NSLog(@"11111");
//长按手势
if (longPress.state == UIGestureRecognizerStateBegan) {
self.myAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您要保存当前图片到相册中吗?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"保存", nil];
[self.myAlertView show];
}
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1) {
// 保存照片(获取到点击的 image)
// NSInteger i = self.scroll.contentOffset.x / self.scroll.bounds.size.width;
UIImageView *myImageView = (UIImageView *)[self.view viewWithTag:10001];
UIImageWriteToSavedPhotosAlbum(myImageView.image, self, @selector(image:didFinshSavingWithError:contextInfo:), nil);
}
}
// 保存图片错误提示方法
- (void)image:(UIImage *)image didFinshSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
NSString *mes = nil;
if (error != nil) {
mes = @"保存图片失败";
} else {
mes = @"保存图片成功";
}
self.myAlertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:mes delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
[self.myAlertView2 show];
[NSTimer scheduledTimerWithTimeInterval:0.8f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
}
- (void)performDismiss:(NSTimer *)timer
{
[self.myAlertView2 dismissWithClickedButtonIndex:0 animated:YES];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end