| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531 |
- //
- // BasicModeViewController.m
- // RA Image
- //
- // Created by Jack on 2017/5/3.
- // Copyright © 2017年 USAI. All rights reserved.
- //
- #import "BasicModeViewController.h"
- #import "ScannerViewController.h"
- #import "PhotoListViewController.h"
- #import "UploadViewController.h"
- #import <AVFoundation/AVFoundation.h>
- #import <AssetsLibrary/AssetsLibrary.h>
- #import "TakePhotoPreviewController.h"
- #pragma clang diagnostic push
- #pragma clang diagnostic ignored "-Wdeprecated-declarations"
- @interface BasicModeViewController ()<UITextFieldDelegate>
- @property (nonatomic,strong) UIImagePickerController *imgPicker;
- @end
- @implementation BasicModeViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- // Do any additional setup after loading the view.
- self.photoCount = 0;
-
- UIBarButtonItem *uploadListItem = [[UIBarButtonItem alloc] initWithTitle:@"Upload List" style:UIBarButtonItemStylePlain target:self action:@selector(showUploadList)];
- self.navigationItem.rightBarButtonItem = uploadListItem;
-
- AppDelegate* appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
-
- [appdelegate.uploadManager addObserver:self
- forKeyPath:@"queue_status"
- options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
- context:@"queue_status changed"];
- }
- -(void) dealloc
- {
- AppDelegate* appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
- [appdelegate.uploadManager removeObserver:self forKeyPath:@"queue_status"];
- }
- - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
- {
-
- if([keyPath isEqualToString:@"queue_status"])
- {
- NSString* msg=@"";
- switch ([[change objectForKey:NSKeyValueChangeNewKey] intValue]) {
- case QueueStatusFinish:
- msg=@"Upload is complete.";
- [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
- break;
- case QueueStatusAdd:
- msg=@"New tasks added.";
- [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
- break;
-
- case QueueStatusFinishWithError:
- {
- NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
- NSDictionary* dict=[userDefaults objectForKey:@"UploadSettingKey"];
- if([dict[@"auto_rm_error"] boolValue])
- msg=@"Upload is complete.";
- else
- msg=@"Some of the tasks have not been successfully uploaded.\n Check upload list for detail.";
-
- [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
- break;
- }
- default:
- break;
- }
- dispatch_async(dispatch_get_main_queue(), ^{
-
- if(msg.length>0)
- [self.view makeToast:msg duration:3.0 position:CSToastPositionCenter];
- });
-
- }
- }
- - (void)didReceiveMemoryWarning {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)viewWillAppear:(BOOL)animated {
- [super viewWillAppear:animated];
-
- }
- - (NSMutableArray *)photos {
- if (!_photos) {
- _photos = [NSMutableArray array];
- }
- return _photos;
- }
- - (void)showUploadList {
-
- UploadViewController *upVC = (UploadViewController *)[self viewControllerInStoryboard:@"Upload" withId:@"UploadViewController"];
- [self.navigationController pushViewController:upVC animated:YES];
- }
- - (void)showPhotoList {
- if (!self.photos.count) {
- // [RAUtils message_alert:@"There is no photo" title:@"Note" controller:self];
- [self showCamera];
- return;
- }
- PhotoListViewController *photoListVC = (PhotoListViewController *)[self viewControllerInStoryboard:@"PhotoList" withId:@"PhotoListViewController"];
- // photoListVC.photos = self.photos;
- photoListVC.modeVC = self;
- [self.navigationController pushViewController:photoListVC animated:YES];
- }
- - (void)showScanner {
- __weak typeof(self) weakself = self;
- ScannerViewController *scannerVC = [[UIStoryboard storyboardWithName:@"cam_scan" bundle:nil] instantiateViewControllerWithIdentifier:@"NewScannerViewController"];
- scannerVC.returnCode = ^(NSString *code) {
- // 扫描成功保存扫描值
- if (code.length) {
-
- if (weakself) {
- __strong typeof(weakself) strongself = weakself;
-
- strongself.barcode = code;
- }
-
- }
- };
- [self presentViewController:scannerVC animated:YES completion:nil];
- }
- - (void)showCamera {
- if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
- [RAUtils message_alert:@"Camera is not available" title:@"Warning" controller:self];
- return;
- }
- //相机权限
- AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
- if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
- authStatus ==AVAuthorizationStatusDenied) //用户已经明确否认了这一照片数据的应用程序访问
- {
- // 无权限 引导去开启
- NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
- if ([[UIApplication sharedApplication]canOpenURL:url]) {
- [[UIApplication sharedApplication]openURL:url];// 打开权限后返回应用会重启
- } else {
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString *appName = [infoDict objectForKey:@"CFBundleName"];
-
- [RAUtils message_alert:[NSString stringWithFormat:@"%@ need Authorization to use Camera",appName] title:@"Warning" controller:self];
- }
- return;
- }
-
- // UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
- // imgPicker.delegate = self;
- //
- // imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
- // imgPicker.allowsEditing = YES;
- // [self presentViewController:imgPicker animated:YES completion:nil];
-
- CGFloat w = CGRectGetWidth(self.view.frame);
- CGFloat h = CGRectGetHeight(self.view.frame);
- if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
- // 修复横屏时打开相机Control位置不正确
- CGFloat tmp = w;
- w = h;
- h = tmp;
- }
- // 自定义相机控制视图
- UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
- imgPicker.delegate = self;
- imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
- imgPicker.allowsEditing = NO;
- imgPicker.showsCameraControls = NO;
- UIView* overlay = [[UIView alloc]initWithFrame:CGRectMake(0, h - 150 , w, 150)];
- // Cancel
- UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- cancelBtn.frame = CGRectMake(20, (150 - 40) * 0.5, 60, 40);
- [cancelBtn setTitle:@"cancel" forState:UIControlStateNormal];
- [cancelBtn addTarget:self action:@selector(cancelCameraClick:) forControlEvents:UIControlEventTouchUpInside];
- [overlay addSubview:cancelBtn];
-
- // Take
- UIButton *takeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- takeBtn.frame = CGRectMake((w - 60) * 0.5, (150 - 40) * 0.5, 60, 40);
- [takeBtn setTitle:@"take" forState:UIControlStateNormal];
- [takeBtn addTarget:self action:@selector(takePhotoClick:) forControlEvents:UIControlEventTouchUpInside];
- [overlay addSubview:takeBtn];
-
- // flash
- UIButton *flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- flashBtn.frame = CGRectMake(w - 80, (150 - 40) * 0.5, 60, 40);
- [flashBtn setTitle:@"Auto" forState:UIControlStateNormal];
- [flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
- [overlay addSubview:flashBtn];
-
- // // camera
- // UIButton *cameraChangeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
- // cameraChangeBtn.frame = CGRectMake(220, 10, 60, 40);
- // [cameraChangeBtn setTitle:@"change" forState:UIControlStateNormal];
- // [cameraChangeBtn addTarget:self action:@selector(cameraChangeClick:) forControlEvents:UIControlEventTouchUpInside];
- // [overlay addSubview:cameraChangeBtn];
-
-
- // 相机属性设置得在设置SourceType后设置
- imgPicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
- //把自定义的view设置到imagepickercontroller的overlay属性中
- imgPicker.cameraOverlayView = overlay;
-
- self.imgPicker = imgPicker;
- [self presentViewController:imgPicker animated:YES completion:nil];
- }
- - (void)showPhotoLibrary {
- if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
- [RAUtils message_alert:@"Photo Library is not available" title:@"Warning" controller:self];
- return;
- }
- //相册权限
- ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
- if (author ==ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
- //无权限 引导去开启
- NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
- if ([[UIApplication sharedApplication] canOpenURL:url]) {
- [[UIApplication sharedApplication] openURL:url];
- } else {
- NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
- NSString *appName = [infoDict objectForKey:@"CFBundleName"];
- [RAUtils message_alert:[NSString stringWithFormat:@"%@ need Authorization to use photo library",appName] title:@"Warning" controller:self];
- }
- return;
- }
-
- UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
- imgPicker.delegate = self;
- imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
- imgPicker.allowsEditing = NO;
- [self presentViewController:imgPicker animated:YES completion:nil];
- }
- - (void)showBarcodeInput:(UIKeyboardType)keyboardType {
- [self tapResignFirstResponder:nil];
- __weak typeof(self) weakself = self;
- UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Please enter %@ Code",self.barcodeTitle] message:nil preferredStyle:UIAlertControllerStyleAlert];
- [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
- textField.text = weakself.barcode;
- textField.delegate = weakself;
- textField.clearButtonMode = UITextFieldViewModeWhileEditing;
- textField.keyboardType = keyboardType;
- }];
-
- UIAlertAction *OK = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
-
- }];
- [alert addAction:OK];
-
- [self presentViewController:alert animated:YES completion:nil];
-
- }
- - (void)showTopImage {
- NSDictionary *item = [self.photos firstObject];
- UIImage *img = [item objectForKey:@"photo"];
- [self receiveImage:img];
- }
- - (NSString *)saveImage:(UIImage *)img {
- NSString *dir = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),self.name];
-
- NSDate * date = [NSDate date];
- NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateFormat:@"YYYYMMddHHmmss"];
- NSString * name = [[dateFormatter stringFromDate:date] stringByAppendingPathExtension:@"png"];
- name=[self.barcodeTitle stringByAppendingString:name];
- // NSString *name = [[NSUUID UUID] UUIDString];
- // name = [name stringByAppendingPathExtension:@"png"];
- NSString *path = [dir stringByAppendingPathComponent:name];
-
- if ([RAUtils saveData:UIImagePNGRepresentation(img) toPath:path]) {
- return path;
- }
-
- return nil;
- }
- //- (void)loadSavedPhotoCount {
- // NSString *dir = [NSString stringWithFormat:@"%@/%@",[RAUtils appCacheDirectory],self.name];
- // NSFileManager *manager = [NSFileManager defaultManager];
- // NSArray *files = [manager contentsOfDirectoryAtPath:dir error:nil];
- // if (files.count) {
- // NSMutableArray *photos = [NSMutableArray array];
- // for (NSString *name in files) {
- // if ([name hasSuffix:@".png"]) {
- // NSString *path = [dir stringByAppendingPathComponent:name];
- // UIImage *img = [UIImage imageWithContentsOfFile:path];
- // NSString *md5 = [RAUtils md5WithFile:path];
- // NSDictionary *photoDic = @{
- // @"photo" : img,
- // @"check" : @(NO),
- // @"path" : path,
- // @"md5" : md5
- // };
- // [photos addObject:photoDic];
- // }
- // }
- // self.photoCount = photos.count;
- // self.photos = photos;
- // } else {
- // self.photoCount = 0;
- // self.photos = nil;
- // }
- //}
- - (void)clearPhotos {
- [self.photos removeAllObjects];
- self.photoCount = 0;
- }
- #pragma mark - Public Method
- - (void)clickCameraButton {
- // __weak typeof(self) weakself = self;
- //
- //
- // UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
- // UIAlertAction *library = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- // [weakself showCamera];
- // }];
- //
- // UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Photo Library" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
- // [weakself showPhotoLibrary];
- // }];
- //
- // UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
- //
- // }];
- //
- // [aler addAction:library];
- // [aler addAction:camera];
- // [aler addAction:cancel];
- //
- // [self presentViewController:aler animated:YES completion:nil];
- [self showCamera];
- }
- - (void)moveTmpImageToCache:(NSString *)img {
-
- NSString *dir = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),self.name];
- NSString *tmpPath = [dir stringByAppendingPathComponent:img];
- NSString *cachePath = [NSString stringWithFormat:@"%@/%@/%@",[RAUtils appCacheDirectory],self.name,img];
-
- NSFileManager *fileManager = [NSFileManager defaultManager];
- // 保证移动目标文件夹存在
- [fileManager createDirectoryAtPath:[cachePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
- NSError *err;
- BOOL res = [fileManager moveItemAtPath:tmpPath toPath:cachePath error:&err];
- if (res) {
- DebugLog(@"move tmp to cache");
- } else {
- DebugLog(@"move tmp to cache failed %@",err);
- }
- }
- #pragma mark - Image Picker Button Action
- - (void)cancelCameraClick:(UIButton *)sender {
- [self.imgPicker dismissViewControllerAnimated:YES completion:nil];
- }
- - (void)takePhotoClick:(UIButton *)sender {
- [self.imgPicker takePicture];
- }
- - (void)flashBtnClick:(UIButton *)sender {
- UIImagePickerControllerCameraDevice device = self.imgPicker.cameraDevice;
- UIImagePickerControllerCameraFlashMode flashMode = self.imgPicker.cameraFlashMode;
- NSString *flashMordeString = @"Auto";
- switch (flashMode) {
- case UIImagePickerControllerCameraFlashModeAuto: {
- flashMode = UIImagePickerControllerCameraFlashModeOn;
- flashMordeString = @"On";
- }
- break;
- case UIImagePickerControllerCameraFlashModeOn: {
- flashMode = UIImagePickerControllerCameraFlashModeOff;
- flashMordeString = @"Off";
- }
- break;
- case UIImagePickerControllerCameraFlashModeOff: {
- flashMode = UIImagePickerControllerCameraFlashModeAuto;
- flashMordeString = @"Auto";
- }
- break;
-
- default:
- break;
- }
-
- if ([UIImagePickerController isFlashAvailableForCameraDevice:device]) {
- self.imgPicker.cameraFlashMode = flashMode;
- [sender setTitle:flashMordeString forState:UIControlStateNormal];
- }
-
- }
- - (void)cameraChangeClick:(UIButton *)sender {
- UIImagePickerControllerCameraDevice device = self.imgPicker.cameraDevice;
- if (device == UIImagePickerControllerCameraDeviceRear) {
- device = UIImagePickerControllerCameraDeviceFront;
- } else {
- device = UIImagePickerControllerCameraDeviceRear;
- }
- if ([UIImagePickerController isCameraDeviceAvailable:device]) {
- self.imgPicker.cameraDevice = device;
- }
-
- }
- #pragma mark - Image Picker Delegate
- - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
- {
- UIImage *image = nil;
- if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
- if (self.imgPicker.viewControllers.count > 1) return;// 避免连续多次拍照,后多次present
- image = [info objectForKey:UIImagePickerControllerOriginalImage];
- // [picker dismissViewControllerAnimated:YES completion:nil];
- __weak typeof(self) weakself = self;
- TakePhotoPreviewController *preVC = (TakePhotoPreviewController *)[self viewControllerInStoryboard:@"Mode" withId:@"TakePhotoPreviewController"];
- __weak typeof(preVC) weakPreVC = preVC;
- preVC.photoHandler = ^(UIImage *img){
- if (img) {
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- NSString *path = [weakself saveImage:img];
- dispatch_async(dispatch_get_main_queue(), ^{
- if (path) {// 保存成功
- [weakself receiveImage:img];
- NSString *md5 = [RAUtils md5WithFile:path];
- NSMutableDictionary *photoDic = @{
- @"photo" : img,
- @"check" : @(NO),
- @"file" : [path lastPathComponent],
- @"md5" : md5,
- @"path" : path
- }.mutableCopy;
- [weakself.photos insertObject:photoDic atIndex:0];
- weakself.photoCount++;
- } else {
- [RAUtils message_alert:@"Save photo failed, storage full?" title:@"Warning" controller:weakPreVC];
- }
- });
-
- });
- }
- };
- preVC.preImage = image;
- [self.imgPicker pushViewController:preVC animated:YES];
-
- } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
-
- image = [info objectForKey:UIImagePickerControllerOriginalImage];
- [picker dismissViewControllerAnimated:YES completion:nil];
- dispatch_async(dispatch_get_global_queue(0, 0), ^{
- NSString *path = [self saveImage:image];
- dispatch_async(dispatch_get_main_queue(), ^{
- if (path) {// 保存成功
- [self receiveImage:image];
- NSString *md5 = [RAUtils md5WithFile:path];
- NSMutableDictionary *photoDic = @{
- @"photo" : image,
- @"check" : @(NO),
- @"file" : [path lastPathComponent],
- @"md5" : md5,
- @"path" : path
- }.mutableCopy;
- [self.photos insertObject:photoDic atIndex:0];
- self.photoCount++;
- } else {
- [RAUtils message_alert:@"Save photo failed, storage full?" title:@"Warning" controller:self];
- }
- });
-
- });
-
- }
-
- }
- - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
-
- [picker dismissViewControllerAnimated:YES completion:nil];
-
-
- }
- #pragma mark - TextField Delegate
- - (void)textFieldDidEndEditing:(UITextField *)textField {
- self.barcode = textField.text;
- }
- #pragma mark - SubClass Override
- - (void)receiveImage:(UIImage *)img {
-
- }
- @end
- #pragma clang diagnostic pop
|