BasicModeViewController.m 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. //
  2. // BasicModeViewController.m
  3. // RA Image
  4. //
  5. // Created by Jack on 2017/5/3.
  6. // Copyright © 2017年 USAI. All rights reserved.
  7. //
  8. #import "BasicModeViewController.h"
  9. #import "ScannerViewController.h"
  10. #import "PhotoListViewController.h"
  11. #import "UploadViewController.h"
  12. #import <AVFoundation/AVFoundation.h>
  13. #import <AssetsLibrary/AssetsLibrary.h>
  14. #import "TakePhotoPreviewController.h"
  15. #import "ImageUtils.h"
  16. #pragma clang diagnostic push
  17. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  18. @interface BasicModeViewController ()<UITextFieldDelegate>
  19. @property (nonatomic,strong) UIImagePickerController *imgPicker;
  20. @end
  21. @implementation BasicModeViewController
  22. - (void)viewDidLoad {
  23. [super viewDidLoad];
  24. // Do any additional setup after loading the view.
  25. self.photoCount = 0;
  26. UIBarButtonItem *uploadListItem = [[UIBarButtonItem alloc] initWithTitle:@"Upload List" style:UIBarButtonItemStylePlain target:self action:@selector(showUploadList)];
  27. self.navigationItem.rightBarButtonItem = uploadListItem;
  28. AppDelegate* appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  29. [appdelegate.uploadManager addObserver:self
  30. forKeyPath:@"queue_status"
  31. options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld)
  32. context:@"queue_status changed"];
  33. if (appdelegate.compressFile) {
  34. [RAUtils message_alert:@"The photos will be compressed" title:@"Attention" controller:self];
  35. }
  36. self.title = self.name;
  37. // UIBarButtonItem *returnItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(returnItemClick:)];
  38. // self.navigationItem.leftBarButtonItem = returnItem;
  39. }
  40. - (void)returnItemClick:(UIBarButtonItem *)sender {
  41. if (self.photoCount > 0) {
  42. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"There are some photos ready to upload,do you wan to discard them?" preferredStyle:UIAlertControllerStyleAlert];
  43. __weak typeof(self) weakSelf = self;
  44. UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  45. [weakSelf.navigationController popViewControllerAnimated:YES];
  46. }];
  47. UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  48. }];
  49. [alert addAction:noAction];
  50. [alert addAction:yesAction];
  51. [self presentViewController:alert animated:YES completion:nil];
  52. } else {
  53. [self.navigationController popViewControllerAnimated:YES];
  54. }
  55. }
  56. -(void) dealloc
  57. {
  58. AppDelegate* appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  59. [appdelegate.uploadManager removeObserver:self forKeyPath:@"queue_status"];
  60. }
  61. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
  62. {
  63. __weak typeof(self) weakself = self;
  64. dispatch_async(dispatch_get_main_queue(), ^{
  65. if([keyPath isEqualToString:@"queue_status"])
  66. {
  67. NSString* msg=@"";
  68. BOOL useToast = NO;
  69. switch ([[change objectForKey:NSKeyValueChangeNewKey] intValue]) {
  70. case QueueStatusFinish: {
  71. msg=@"Upload is complete.";
  72. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  73. useToast = NO;
  74. }
  75. break;
  76. case QueueStatusAdd: {
  77. msg=@"New tasks added.";
  78. [[UIApplication sharedApplication] setIdleTimerDisabled:YES];
  79. useToast = YES;
  80. }
  81. break;
  82. case QueueStatusFinishWithError:
  83. {
  84. NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
  85. NSDictionary* dict=[userDefaults objectForKey:@"UploadSettingKey"];
  86. if([dict[@"auto_rm_error"] boolValue])
  87. msg=@"Upload is complete.";
  88. else
  89. msg=@"Some of the tasks have not been successfully uploaded.\n Check upload list for detail.";
  90. [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
  91. useToast = NO;
  92. }
  93. break;
  94. default:
  95. break;
  96. }
  97. if(msg.length>0) {
  98. if (useToast) {
  99. [weakself.view makeToast:msg duration:3.0 position:CSToastPositionCenter];
  100. } else {
  101. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:msg preferredStyle:UIAlertControllerStyleAlert];
  102. UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  103. }];
  104. [alert addAction:action];
  105. [weakself presentViewController:alert animated:YES completion:nil];
  106. }
  107. }
  108. }
  109. });
  110. }
  111. - (void)didReceiveMemoryWarning {
  112. [super didReceiveMemoryWarning];
  113. // Dispose of any resources that can be recreated.
  114. }
  115. - (void)viewWillAppear:(BOOL)animated {
  116. [super viewWillAppear:animated];
  117. }
  118. - (NSMutableArray *)photos {
  119. if (!_photos) {
  120. _photos = [NSMutableArray array];
  121. }
  122. return _photos;
  123. }
  124. - (void)showUploadList {
  125. UploadViewController *upVC = (UploadViewController *)[self viewControllerInStoryboard:@"Upload" withId:@"UploadViewController"];
  126. [self.navigationController pushViewController:upVC animated:YES];
  127. }
  128. - (void)showPhotoList {
  129. if (!self.photos.count) {
  130. // [RAUtils message_alert:@"There is no photo" title:@"Note" controller:self];
  131. [self showCamera];
  132. return;
  133. }
  134. PhotoListViewController *photoListVC = (PhotoListViewController *)[self viewControllerInStoryboard:@"PhotoList" withId:@"PhotoListViewController"];
  135. // photoListVC.photos = self.photos;
  136. photoListVC.modeVC = self;
  137. [self.navigationController pushViewController:photoListVC animated:YES];
  138. }
  139. - (void)showScanner {
  140. __weak typeof(self) weakself = self;
  141. ScannerViewController *scannerVC = [[UIStoryboard storyboardWithName:@"cam_scan" bundle:nil] instantiateViewControllerWithIdentifier:@"NewScannerViewController"];
  142. scannerVC.returnCode = ^(NSString *code) {
  143. // 扫描成功保存扫描值
  144. if (code.length) {
  145. if (weakself) {
  146. __strong typeof(weakself) strongself = weakself;
  147. strongself.barcode = code;
  148. }
  149. }
  150. };
  151. [self presentViewController:scannerVC animated:YES completion:nil];
  152. }
  153. - (void)showCamera {
  154. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  155. [RAUtils message_alert:@"Camera is not available" title:@"Warning" controller:self];
  156. return;
  157. }
  158. //相机权限
  159. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  160. if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
  161. authStatus ==AVAuthorizationStatusDenied) //用户已经明确否认了这一照片数据的应用程序访问
  162. {
  163. // 无权限 引导去开启
  164. NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  165. if ([[UIApplication sharedApplication]canOpenURL:url]) {
  166. [[UIApplication sharedApplication]openURL:url];// 打开权限后返回应用会重启
  167. } else {
  168. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  169. NSString *appName = [infoDict objectForKey:@"CFBundleName"];
  170. [RAUtils message_alert:[NSString stringWithFormat:@"%@ need Authorization to use Camera",appName] title:@"Warning" controller:self];
  171. }
  172. return;
  173. }
  174. // UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
  175. // imgPicker.delegate = self;
  176. //
  177. // imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  178. // imgPicker.allowsEditing = YES;
  179. // [self presentViewController:imgPicker animated:YES completion:nil];
  180. CGFloat w = CGRectGetWidth(self.view.frame);
  181. CGFloat h = CGRectGetHeight(self.view.frame);
  182. if (self.interfaceOrientation == UIInterfaceOrientationLandscapeLeft || self.interfaceOrientation == UIInterfaceOrientationLandscapeRight) {
  183. // 修复横屏时打开相机Control位置不正确
  184. CGFloat tmp = w;
  185. w = h;
  186. h = tmp;
  187. }
  188. // 自定义相机控制视图
  189. UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
  190. imgPicker.delegate = self;
  191. imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
  192. imgPicker.allowsEditing = NO;
  193. imgPicker.showsCameraControls = NO;
  194. UIView* overlay = [[UIView alloc]initWithFrame:CGRectMake(0, h - 150 , w, 150)];
  195. // Cancel
  196. UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  197. cancelBtn.frame = CGRectMake(20, (150 - 40) * 0.5, 60, 40);
  198. [cancelBtn setTitle:@"cancel" forState:UIControlStateNormal];
  199. [cancelBtn addTarget:self action:@selector(cancelCameraClick:) forControlEvents:UIControlEventTouchUpInside];
  200. [overlay addSubview:cancelBtn];
  201. // Take
  202. UIButton *takeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  203. takeBtn.frame = CGRectMake((w - 60) * 0.5, (150 - 60) * 0.5, 60, 60);
  204. // [takeBtn setTitle:@"take" forState:UIControlStateNormal];
  205. [takeBtn setImage:[UIImage imageNamed:@"take_photo"] forState:UIControlStateNormal];
  206. [takeBtn addTarget:self action:@selector(takePhotoClick:) forControlEvents:UIControlEventTouchUpInside];
  207. [overlay addSubview:takeBtn];
  208. // flash
  209. UIButton *flashBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  210. flashBtn.frame = CGRectMake(w - 80, (150 - 60) * 0.5, 60, 60);
  211. [flashBtn setImage:[UIImage imageNamed:@"flash_auto"] forState:UIControlStateNormal];
  212. [flashBtn addTarget:self action:@selector(flashBtnClick:) forControlEvents:UIControlEventTouchUpInside];
  213. [overlay addSubview:flashBtn];
  214. // // camera
  215. // UIButton *cameraChangeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  216. // cameraChangeBtn.frame = CGRectMake(220, 10, 60, 40);
  217. // [cameraChangeBtn setTitle:@"change" forState:UIControlStateNormal];
  218. // [cameraChangeBtn addTarget:self action:@selector(cameraChangeClick:) forControlEvents:UIControlEventTouchUpInside];
  219. // [overlay addSubview:cameraChangeBtn];
  220. // 相机属性设置得在设置SourceType后设置
  221. imgPicker.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
  222. //把自定义的view设置到imagepickercontroller的overlay属性中
  223. imgPicker.cameraOverlayView = overlay;
  224. self.imgPicker = imgPicker;
  225. [self presentViewController:imgPicker animated:YES completion:nil];
  226. }
  227. - (void)showPhotoLibrary {
  228. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
  229. [RAUtils message_alert:@"Photo Library is not available" title:@"Warning" controller:self];
  230. return;
  231. }
  232. //相册权限
  233. ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
  234. if (author ==ALAuthorizationStatusRestricted || author ==ALAuthorizationStatusDenied){
  235. //无权限 引导去开启
  236. NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  237. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  238. [[UIApplication sharedApplication] openURL:url];
  239. } else {
  240. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  241. NSString *appName = [infoDict objectForKey:@"CFBundleName"];
  242. [RAUtils message_alert:[NSString stringWithFormat:@"%@ need Authorization to use photo library",appName] title:@"Warning" controller:self];
  243. }
  244. return;
  245. }
  246. UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
  247. imgPicker.delegate = self;
  248. imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  249. imgPicker.allowsEditing = NO;
  250. [self presentViewController:imgPicker animated:YES completion:nil];
  251. }
  252. - (void)showBarcodeInput:(UIKeyboardType)keyboardType {
  253. [self tapResignFirstResponder:nil];
  254. __weak typeof(self) weakself = self;
  255. UIAlertController *alert = [UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"Please enter %@ Code",self.barcodeTitle] message:nil preferredStyle:UIAlertControllerStyleAlert];
  256. [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  257. textField.text = weakself.barcode;
  258. textField.delegate = weakself;
  259. textField.clearButtonMode = UITextFieldViewModeWhileEditing;
  260. textField.keyboardType = keyboardType;
  261. }];
  262. UIAlertAction *OK = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  263. }];
  264. [alert addAction:OK];
  265. [self presentViewController:alert animated:YES completion:nil];
  266. }
  267. - (void)showTopImage {
  268. NSDictionary *item = [self.photos firstObject];
  269. UIImage *img = [UIImage imageWithContentsOfFile:[item objectForKey:@"path"]];
  270. [self receiveImage:img];
  271. }
  272. - (NSString *)saveImage:(UIImage *)img {
  273. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  274. if (appDelegate.compressFile) {
  275. img = [ImageUtils img_compress:img kbsize:1024];
  276. }
  277. // NSString *dir = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),self.name];
  278. // V1.07 之后图片不再保存到Temp
  279. NSString *dir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  280. NSDate * date = [NSDate date];
  281. NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
  282. [dateFormatter setDateFormat:@"YYYYMMdd_HHmmssSS"];
  283. NSString * name = [[dateFormatter stringFromDate:date] stringByAppendingPathExtension:@"png"];
  284. name=[self.barcodeTitle stringByAppendingString:name];
  285. // NSString *name = [[NSUUID UUID] UUIDString];
  286. // name = [name stringByAppendingPathExtension:@"png"];
  287. NSString *path = [dir stringByAppendingPathComponent:name];
  288. if ([RAUtils saveData:UIImagePNGRepresentation(img) toPath:path]) {
  289. return path;
  290. }
  291. return nil;
  292. }
  293. //- (void)loadSavedPhotoCount {
  294. // NSString *dir = [NSString stringWithFormat:@"%@/%@",[RAUtils appCacheDirectory],self.name];
  295. // NSFileManager *manager = [NSFileManager defaultManager];
  296. // NSArray *files = [manager contentsOfDirectoryAtPath:dir error:nil];
  297. // if (files.count) {
  298. // NSMutableArray *photos = [NSMutableArray array];
  299. // for (NSString *name in files) {
  300. // if ([name hasSuffix:@".png"]) {
  301. // NSString *path = [dir stringByAppendingPathComponent:name];
  302. // UIImage *img = [UIImage imageWithContentsOfFile:path];
  303. // NSString *md5 = [RAUtils md5WithFile:path];
  304. // NSDictionary *photoDic = @{
  305. // @"photo" : img,
  306. // @"check" : @(NO),
  307. // @"path" : path,
  308. // @"md5" : md5
  309. // };
  310. // [photos addObject:photoDic];
  311. // }
  312. // }
  313. // self.photoCount = photos.count;
  314. // self.photos = photos;
  315. // } else {
  316. // self.photoCount = 0;
  317. // self.photos = nil;
  318. // }
  319. //}
  320. - (void)clearPhotos {
  321. [self.photos removeAllObjects];
  322. self.photoCount = 0;
  323. }
  324. #pragma mark - Public Method
  325. - (void)clickCameraButton {
  326. // __weak typeof(self) weakself = self;
  327. //
  328. //
  329. // UIAlertController *aler = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
  330. // UIAlertAction *library = [UIAlertAction actionWithTitle:@"Camera" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  331. // [weakself showCamera];
  332. // }];
  333. //
  334. // UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Photo Library" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  335. // [weakself showPhotoLibrary];
  336. // }];
  337. //
  338. // UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  339. //
  340. // }];
  341. //
  342. // [aler addAction:library];
  343. // [aler addAction:camera];
  344. // [aler addAction:cancel];
  345. //
  346. // [self presentViewController:aler animated:YES completion:nil];
  347. [self showCamera];
  348. }
  349. - (void)moveTmpImageToCache:(NSString *)img {
  350. // V1.07 之后图片不再保存到Temp
  351. BOOL a = 0; // 避免警告
  352. if (a == 0) {
  353. return;
  354. }
  355. NSString *dir = [NSString stringWithFormat:@"%@/%@",NSTemporaryDirectory(),self.name];
  356. NSString *tmpPath = [dir stringByAppendingPathComponent:img];
  357. NSString *cachePath = [NSString stringWithFormat:@"%@/%@/%@",[RAUtils appCacheDirectory],self.name,img];
  358. NSFileManager *fileManager = [NSFileManager defaultManager];
  359. // 保证移动目标文件夹存在
  360. [fileManager createDirectoryAtPath:[cachePath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
  361. NSError *err;
  362. BOOL res = [fileManager moveItemAtPath:tmpPath toPath:cachePath error:&err];
  363. if (res) {
  364. DebugLog(@"move tmp to cache");
  365. } else {
  366. DebugLog(@"move tmp to cache failed %@",err);
  367. }
  368. }
  369. - (BOOL)shouldUploadWithCurrentNerworkStatus {
  370. AppDelegate* appdelegate=(AppDelegate*)[UIApplication sharedApplication].delegate;
  371. if (appdelegate.uploadManager.onlyWiFi && appdelegate.uploadManager.reach.currentReachabilityStatus != ReachableViaWiFi) {
  372. return NO;
  373. }
  374. return YES;
  375. }
  376. #pragma mark - Image Picker Button Action
  377. - (void)cancelCameraClick:(UIButton *)sender {
  378. [self.imgPicker dismissViewControllerAnimated:YES completion:nil];
  379. }
  380. - (void)takePhotoClick:(UIButton *)sender {
  381. [self.imgPicker takePicture];
  382. }
  383. - (void)flashBtnClick:(UIButton *)sender {
  384. UIImagePickerControllerCameraDevice device = self.imgPicker.cameraDevice;
  385. UIImagePickerControllerCameraFlashMode flashMode = self.imgPicker.cameraFlashMode;
  386. NSString *flashMordeString = @"flash_auto";
  387. UIImage *flash_img = [UIImage imageNamed:flashMordeString];
  388. switch (flashMode) {
  389. case UIImagePickerControllerCameraFlashModeAuto: {
  390. flashMode = UIImagePickerControllerCameraFlashModeOn;
  391. flashMordeString = @"flash_on";
  392. flash_img = [UIImage imageNamed:flashMordeString];
  393. }
  394. break;
  395. case UIImagePickerControllerCameraFlashModeOn: {
  396. flashMode = UIImagePickerControllerCameraFlashModeOff;
  397. flashMordeString = @"flash_off";
  398. flash_img = [UIImage imageNamed:flashMordeString];
  399. }
  400. break;
  401. case UIImagePickerControllerCameraFlashModeOff: {
  402. flashMode = UIImagePickerControllerCameraFlashModeAuto;
  403. flashMordeString = @"flash_auto";
  404. flash_img = [UIImage imageNamed:flashMordeString];
  405. }
  406. break;
  407. default:
  408. break;
  409. }
  410. if ([UIImagePickerController isFlashAvailableForCameraDevice:device]) {
  411. self.imgPicker.cameraFlashMode = flashMode;
  412. [sender setImage:[UIImage imageNamed:flashMordeString] forState:UIControlStateNormal];
  413. }
  414. }
  415. - (void)cameraChangeClick:(UIButton *)sender {
  416. UIImagePickerControllerCameraDevice device = self.imgPicker.cameraDevice;
  417. if (device == UIImagePickerControllerCameraDeviceRear) {
  418. device = UIImagePickerControllerCameraDeviceFront;
  419. } else {
  420. device = UIImagePickerControllerCameraDeviceRear;
  421. }
  422. if ([UIImagePickerController isCameraDeviceAvailable:device]) {
  423. self.imgPicker.cameraDevice = device;
  424. }
  425. }
  426. #pragma mark - Image Picker Delegate
  427. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
  428. {
  429. UIImage *image = nil;
  430. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  431. if (self.imgPicker.viewControllers.count > 1) return;// 避免连续多次拍照,后多次present
  432. image = [info objectForKey:UIImagePickerControllerOriginalImage];
  433. // [picker dismissViewControllerAnimated:YES completion:nil];
  434. __weak typeof(self) weakself = self;
  435. TakePhotoPreviewController *preVC = (TakePhotoPreviewController *)[self viewControllerInStoryboard:@"Mode" withId:@"TakePhotoPreviewController"];
  436. __weak typeof(preVC) weakPreVC = preVC;
  437. preVC.photoHandler = ^(UIImage *img){
  438. if (img) {
  439. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  440. NSString *path = [weakself saveImage:img];
  441. dispatch_async(dispatch_get_main_queue(), ^{
  442. if (path) {// 保存成功
  443. [weakself receiveImage:img];
  444. NSString *md5 = [RAUtils md5WithFile:path];
  445. NSMutableDictionary *photoDic = @{
  446. @"check" : @(NO),
  447. @"file" : [path lastPathComponent],
  448. @"md5" : md5,
  449. @"path" : path,
  450. }.mutableCopy;
  451. [weakself.photos insertObject:photoDic atIndex:0];
  452. weakself.photoCount++;
  453. } else {
  454. [RAUtils message_alert:@"Save photo failed, storage full?" title:@"Warning" controller:weakPreVC];
  455. }
  456. });
  457. });
  458. }
  459. };
  460. preVC.preImage = image;
  461. [self.imgPicker pushViewController:preVC animated:YES];
  462. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  463. image = [info objectForKey:UIImagePickerControllerOriginalImage];
  464. [picker dismissViewControllerAnimated:YES completion:nil];
  465. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  466. NSString *path = [self saveImage:image];
  467. dispatch_async(dispatch_get_main_queue(), ^{
  468. if (path) {// 保存成功
  469. [self receiveImage:image];
  470. NSString *md5 = [RAUtils md5WithFile:path];
  471. NSMutableDictionary *photoDic = @{
  472. @"check" : @(NO),
  473. @"file" : [path lastPathComponent],
  474. @"md5" : md5,
  475. @"path" : path,
  476. }.mutableCopy;
  477. [self.photos insertObject:photoDic atIndex:0];
  478. self.photoCount++;
  479. } else {
  480. [RAUtils message_alert:@"Save photo failed, storage full?" title:@"Warning" controller:self];
  481. }
  482. });
  483. });
  484. }
  485. }
  486. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  487. [picker dismissViewControllerAnimated:YES completion:nil];
  488. }
  489. #pragma mark - TextField Delegate
  490. - (void)textFieldDidEndEditing:(UITextField *)textField {
  491. self.barcode = textField.text;
  492. }
  493. #pragma mark - SubClass Override
  494. - (void)receiveImage:(UIImage *)img {
  495. }
  496. -(void) verify:(NSMutableDictionary*) params
  497. {
  498. AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
  499. // appDelegate.address = self.address;
  500. __weak typeof(self) weakself = self;
  501. NSString* title=[@"Verify " stringByAppendingString:self.barcodeTitle];
  502. UIAlertView *alert = [RAUtils waiting_alert:@"Please wait" title:title];
  503. dispatch_async(dispatch_get_global_queue(0, 0), ^{
  504. // if (weakself) {
  505. // __strong typeof(weakself) strongself = weakself;
  506. NSDictionary *result_json = [RANetwork Verify:params];
  507. dispatch_async(dispatch_get_main_queue(), ^{
  508. [alert dismissWithClickedButtonIndex:0 animated:YES];
  509. int result = [[result_json objectForKey:@"result"] intValue];
  510. // BOOL rememberLogin = [[strongself userDefaultsValue:kRememberLogin] boolValue];
  511. // [self addTasks];
  512. // return;
  513. switch (result) {
  514. case 0:
  515. {
  516. //code not exist;
  517. [RAUtils message_alert:weakself.verify_msg0 title:@"Warring" controller:weakself];
  518. // [weakself.view makeToast:weakself.verify_msg0 duration:3.0 position:CSToastPositionCenter];
  519. break;
  520. }
  521. case 1:
  522. {
  523. [RAUtils message_alert:@"Model/Manufacturer does not match" title:@"Warring" controller:weakself];
  524. // [weakself.view makeToast:@"Model/Manufacturer does not match" duration:3.0 position:CSToastPositionCenter];
  525. break;
  526. }
  527. case 2:
  528. {
  529. //upload;
  530. [self addTasks];
  531. break;
  532. }
  533. case RESULT_NET_ERROR:
  534. {
  535. __weak typeof(self) weakSelf = self;
  536. UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"Warning" message:@"Can not connect to server,still upload?" preferredStyle:UIAlertControllerStyleAlert];
  537. UIAlertAction *yesAction = [UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  538. [weakSelf addTasks];
  539. }];
  540. UIAlertAction *noAction = [UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
  541. }];
  542. [alertVC addAction:yesAction];
  543. [alertVC addAction:noAction];
  544. [self presentViewController:alertVC animated:yesAction completion:nil];
  545. }
  546. default:
  547. break;
  548. }
  549. });
  550. // }
  551. });
  552. }
  553. @end
  554. #pragma clang diagnostic pop