ScannerViewController.m 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. /*
  2. Copyright 2013 Scott Logic Ltd
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. #import "ScannerViewController.h"
  14. @import AVFoundation;
  15. #import <AudioToolbox/AudioToolbox.h>
  16. #import "SCShapeView.h"
  17. #import "ScannerControllerView.h"
  18. //#import "DetailViewController.h"
  19. #import "const.h"
  20. #import "AppDelegate.h"
  21. //#import "MainViewController.h"
  22. //#import "ContactListViewController.h"
  23. //#import "CartUtils.h"
  24. #define SCANNER_TARGET_DETAIL 0
  25. #define SCANNER_TARGET_CART 1
  26. //#import "ScannerControlViewController.h"
  27. @interface ScannerViewController () <AVCaptureMetadataOutputObjectsDelegate> {
  28. AVCaptureVideoPreviewLayer *_previewLayer;
  29. SCShapeView *_boundingBox;
  30. NSTimer *_boxHideTimer;
  31. UILabel *_decodedMessage;
  32. }
  33. @end
  34. @implementation ScannerViewController
  35. //- (UIInterfaceOrientationMask)supportedInterfaceOrientations
  36. //{
  37. // return UIInterfaceOrientationMaskPortrait;
  38. //}
  39. //- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
  40. //{
  41. //
  42. // return (toInterfaceOrientation == UIInterfaceOrientationPortrait);
  43. //
  44. //}
  45. - (BOOL)shouldAutorotate
  46. {
  47. return false;
  48. }
  49. -(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  50. {
  51. [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
  52. CGRect rect=self.view.bounds;
  53. DebugLog(NSStringFromCGRect(self.focusZone.frame));
  54. // rect.origin.y=rect.origin.y+40;
  55. // rect.size.height = rect.size.height-40;
  56. [CATransaction begin];
  57. [CATransaction setAnimationDuration:0.5];
  58. [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  59. // [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  60. _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  61. // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  62. _previewLayer.bounds = rect;
  63. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  64. switch (orientation) {
  65. case UIInterfaceOrientationPortrait:
  66. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  67. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  68. break;
  69. case UIInterfaceOrientationPortraitUpsideDown:
  70. //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  71. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  72. break;
  73. case UIInterfaceOrientationLandscapeLeft:
  74. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  75. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  76. break;
  77. case UIInterfaceOrientationLandscapeRight:
  78. // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  79. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  80. break;
  81. default:
  82. break;
  83. }
  84. [CATransaction commit];
  85. }
  86. //- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
  87. //{
  88. // return UIInterfaceOrientationPortrait;
  89. //}
  90. -(void) playSound
  91. {
  92. /*
  93. SystemSoundID sameViewSoundID;
  94. // NSString *filePath = [[NSBundle mainBundle]pathForResource:@"sound" ofType:@"m4r"];
  95. // NSString *thesoundFilePath = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]; //音乐文件路径
  96. NSString *path = @"/System/Library/Audio/UISounds/begin_video_record.caf";
  97. CFURLRef thesoundURL = (__bridge CFURLRef) [NSURL fileURLWithPath:path] ;
  98. AudioServicesCreateSystemSoundID(thesoundURL, &sameViewSoundID);
  99. //变量SoundID与URL对应
  100. DebugLog(@"%u",(unsigned int)sameViewSoundID);
  101. AudioServicesPlaySystemSound(1112); //播放SoundID声音
  102. */
  103. CFBundleRef mainBundle;
  104. SystemSoundID soundFileObject;
  105. mainBundle = CFBundleGetMainBundle ();
  106. CFURLRef soundFileURLRef = CFBundleCopyResourceURL (
  107. mainBundle,
  108. CFSTR ("softScanBeep" ),
  109. CFSTR ("wav" ),
  110. NULL
  111. );
  112. AudioServicesCreateSystemSoundID (
  113. soundFileURLRef,
  114. &soundFileObject
  115. );
  116. AudioServicesPlaySystemSound(soundFileObject);
  117. }
  118. - (void)viewWillAppear:(BOOL)animated
  119. {
  120. [super viewWillAppear:animated];
  121. [[self navigationController] setNavigationBarHidden:NO animated:NO];
  122. //
  123. //[ attemptRotationToDeviceOrientation];
  124. //[UIViewController attemptRotationToDeviceOrientation];
  125. //
  126. // [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
  127. // self.view.transform = CGAffineTransformMakeRotation(M_PI/2);
  128. // CGRect frame = [UIScreen mainScreen].applicationFrame;
  129. // self.view.bounds = CGRectMake(0, 0, 768, 1024);
  130. }
  131. - (void)onBackClick:(UIButton *)sender {
  132. [self.navigationController popViewControllerAnimated:FALSE];
  133. }
  134. - (void)viewDidLoad
  135. {
  136. [super viewDidLoad];
  137. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  138. style:UIBarButtonItemStylePlain
  139. target:self
  140. action:@selector( onBackClick:)];
  141. // closeButton.tintColor = UIColorFromRGB(0x996633);
  142. self.navigationItem.leftBarButtonItem = closeButton;
  143. }
  144. - (void)viewDidAppear:(BOOL)animated {
  145. [super viewDidAppear:animated];
  146. // 只有在此方法中取得的self.focusZone.frame才正确。
  147. // return;
  148. // [self.backgroundView removeFromSuperview];
  149. //self.back = (ScannerControllerView*)self.view;
  150. self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  151. [self.backgroundView setNeedsDisplay];
  152. // self.backgroundView.autoresizingMask=0xff;
  153. self.handelOutput = false;
  154. // self.ScannerControl =[self.storyboard instantiateViewControllerWithIdentifier:@"ScannerControlViewController"];
  155. // self.ScannerControl.Scannerdelegate = self;
  156. // self.view.layer.
  157. // Do any additional setup after loading the view, typically from a nib.
  158. // Create a new AVCaptureSession
  159. AVCaptureSession *session = [[AVCaptureSession alloc] init];
  160. session.sessionPreset = AVCaptureSessionPresetHigh;
  161. AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
  162. // float factor = device.videoZoomFactor;
  163. // float up = device.activeFormat.videoZoomFactorUpscaleThreshold;
  164. // [device lockForConfiguration:nil];
  165. // device.videoZoomFactor = device.activeFormat.videoZoomFactorUpscaleThreshold;
  166. // [device unlockForConfiguration];
  167. NSError *error = nil;
  168. // Want the normal device
  169. AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
  170. if(input) {
  171. // Add the input to the session
  172. [session addInput:input];
  173. } else {
  174. __weak typeof(self) weakself = self;
  175. // UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"Camera access denied, please change iPad setting, allow App use camara. (setting -> privacy -> camera enable RA Image)" preferredStyle:UIAlertControllerStyleAlert];
  176. // UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  177. // [weakself dismissViewControllerAnimated:YES completion:nil];
  178. // }];
  179. // [alert addAction:action];
  180. // [self presentViewController:alert animated:YES completion:nil];
  181. if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) { // 设备不可用
  182. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:@"Camera is not available" preferredStyle:UIAlertControllerStyleAlert];
  183. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  184. [weakself dismissViewControllerAnimated:YES completion:nil];
  185. }];
  186. [alert addAction:action];
  187. [self presentViewController:alert animated:YES completion:nil];
  188. return;
  189. }
  190. // 相机权限
  191. AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  192. if (authStatus ==AVAuthorizationStatusRestricted ||//此应用程序没有被授权访问的照片数据。可能是家长控制权限
  193. authStatus ==AVAuthorizationStatusDenied) //用户已经明确否认了这一照片数据的应用程序访问
  194. {
  195. // 无权限 引导去开启
  196. // NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  197. // if ([[UIApplication sharedApplication]canOpenURL:url]) {
  198. // [[UIApplication sharedApplication]openURL:url];// 打开权限后返回应用会重启
  199. // } else {
  200. NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
  201. NSString *appName = [infoDict objectForKey:@"CFBundleName"];
  202. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Warning" message:[NSString stringWithFormat:@"Camera access denied, please change %@ setting, allow App use camera. (setting -> privacy -> camera enable %@)",[UIDevice currentDevice].model,appName] preferredStyle:UIAlertControllerStyleAlert];
  203. UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  204. [weakself dismissViewControllerAnimated:YES completion:nil];
  205. }];
  206. [alert addAction:action];
  207. [self presentViewController:alert animated:YES completion:nil];
  208. // }
  209. return;
  210. }
  211. return;
  212. }
  213. AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
  214. // Have to add the output before setting metadata types
  215. [session addOutput:output];
  216. // What different things can we register to recognise?
  217. DebugLog(@"%@", [output availableMetadataObjectTypes]);
  218. // We're only interested in QR Codes
  219. [output setMetadataObjectTypes:@[AVMetadataObjectTypeUPCECode,AVMetadataObjectTypeCode39Code,AVMetadataObjectTypeCode39Mod43Code,AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeEAN8Code,AVMetadataObjectTypeCode93Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeQRCode,AVMetadataObjectTypeAztecCode]];
  220. DebugLog(@"%@", [output metadataObjectTypes]);
  221. // NSArray* supporttype=output.availableMetadataObjectTypes;
  222. // [output setMetadataObjectTypes:output.availableMetadataObjectTypes];
  223. // This VC is the delegate. Please call us on the main queue
  224. [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
  225. //
  226. // CGRect rt1 = self.ScannerControl.scannerZone.frame;
  227. // Display on screen
  228. _previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:session];
  229. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  230. // _previewLayer.orientation= AVCaptureVideoOrientationLandscapeRight;
  231. UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  232. switch (orientation) {
  233. // UIInterfaceOrientationPortrait = UIDeviceOrientationPortrait,
  234. // UIInterfaceOrientationPortraitUpsideDown = UIDeviceOrientationPortraitUpsideDown,
  235. // UIInterfaceOrientationLandscapeLeft = UIDeviceOrientationLandscapeRight,
  236. // UIInterfaceOrientationLandscapeRight
  237. // AVCaptureVideoOrientationPortrait = 1,
  238. // AVCaptureVideoOrientationPortraitUpsideDown = 2,
  239. // AVCaptureVideoOrientationLandscapeRight = 3,
  240. // AVCaptureVideoOrientationLandscapeLeft = 4,
  241. case UIInterfaceOrientationPortrait:
  242. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  243. break;
  244. case UIInterfaceOrientationPortraitUpsideDown:
  245. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  246. break;
  247. case UIInterfaceOrientationLandscapeLeft:
  248. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  249. break;
  250. case UIInterfaceOrientationLandscapeRight:
  251. _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  252. break;
  253. default:
  254. break;
  255. }
  256. CGRect rect=self.view.bounds;
  257. // rect.origin.y=rect.origin.y+40;
  258. // rect.size.height = rect.size.height-40;
  259. _previewLayer.bounds = rect;
  260. _previewLayer.position = CGPointMake(CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds));
  261. // [self.view.layer addSublayer:_previewLayer];
  262. [self.view.layer insertSublayer:_previewLayer atIndex:0];
  263. // [self.view addSubview:self.backgroundView];
  264. [self.view bringSubviewToFront:self.backgroundView];
  265. // [self.view addSubview:self.ScannerControl.view];
  266. // CGRect rt = self.ScannerControl.scannerZone.bounds;
  267. // CGRect rt1 =output.rectOfInterest;
  268. // output.rectOfInterest = CGRectMake(0, 0, 300, 300); //self.ScannerControl.scannerZone.frame;
  269. // ScannerControllerView* view =[[ ScannerControllerView alloc] initWithFrame:self.view.frame];
  270. // view.backgroundColor = [UIColor clearColor];
  271. // ScannerLayer * layer = [[ScannerLayer alloc] init];
  272. // [self.view.layer addSublayer:layer];
  273. // Add the view to draw the bounding box for the UIView
  274. _boundingBox = [[SCShapeView alloc] initWithFrame:self.view.bounds];
  275. _boundingBox.backgroundColor = [UIColor clearColor];
  276. _boundingBox.hidden = YES;
  277. [self.view insertSubview:_boundingBox belowSubview:self.backgroundView];
  278. // Add a label to display the resultant message
  279. _decodedMessage = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetHeight(self.view.bounds) - 75, CGRectGetWidth(self.view.bounds), 75)];
  280. _decodedMessage.numberOfLines = 0;
  281. _decodedMessage.backgroundColor = [UIColor colorWithWhite:0.8 alpha:0.9];
  282. _decodedMessage.textColor = [UIColor darkGrayColor];
  283. _decodedMessage.textAlignment = NSTextAlignmentCenter;
  284. [self.view addSubview:_decodedMessage];
  285. _decodedMessage.userInteractionEnabled = YES;
  286. UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
  287. [backBtn setTitle:@"Cancel" forState:UIControlStateNormal];
  288. backBtn.titleLabel.backgroundColor = [UIColor clearColor];
  289. backBtn.titleLabel.font = [UIFont systemFontOfSize: 18.0];
  290. [backBtn setTitleColor:UIColorFromRGB(0x007aff) forState:UIControlStateNormal];
  291. backBtn.frame = CGRectMake(CGRectGetMaxX(self.view.frame) - 80, CGRectGetMaxY(self.view.frame)-CGRectGetHeight(_decodedMessage.frame), 60, CGRectGetHeight(_decodedMessage.frame));
  292. [self.view addSubview:backBtn];
  293. [backBtn addTarget:self action:@selector(backButtonClick:) forControlEvents:UIControlEventTouchUpInside];
  294. self.scanButton.layer.shadowColor = [UIColor blackColor].CGColor;
  295. self.scanButton.layer.shadowOffset = CGSizeMake(0, 0);
  296. self.scanButton.layer.shadowOpacity = 0.5;
  297. self.scanButton.layer.shadowRadius = 2.0;
  298. self.scanButton.layer.borderColor = [[UIColor darkGrayColor] CGColor];
  299. self.scanButton.layer.borderWidth = 15;
  300. // Start the AVSession running
  301. [session startRunning];
  302. }
  303. - (void)backButtonClick:(UIButton *)sender {
  304. [self dismissViewControllerAnimated:YES completion:nil];
  305. }
  306. //#pragma mark - ScannerControllerDelegate
  307. //-(void)BeginScan:(bool)begin
  308. //{
  309. // self.handelOutput = begin;
  310. //}
  311. #pragma mark - AVCaptureMetadataOutputObjectsDelegate
  312. - (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
  313. {
  314. if(!self.handelOutput)
  315. return;
  316. AVMetadataObject * cadedate = nil;
  317. CGPoint centerzone =CGPointMake(CGRectGetMidX(self.focusZone.frame), CGRectGetMidY(self.focusZone.frame));
  318. float distance = MAXFLOAT;
  319. for (AVMetadataObject *metadata in metadataObjects) {
  320. DebugLog(@"%@",metadata);
  321. // if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode])
  322. {
  323. // Transform the meta-data coordinates to screen coords
  324. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:metadata];
  325. // Update the frame on the _boundingBox view, and show it
  326. CGRect rt = transformed.bounds;
  327. CGRectGetMidX(rt);
  328. CGPoint centermeta =CGPointMake(CGRectGetMidX(rt), CGRectGetMidY(rt));
  329. if(CGRectContainsPoint(self.focusZone.frame, centermeta))
  330. {
  331. if(cadedate == nil)
  332. cadedate = metadata;
  333. float distancemeta = (centermeta.x-centerzone.x)*(centermeta.x-centerzone.x)+(centermeta.y-centerzone.y)*(centermeta.y-centerzone.y);
  334. if(distancemeta<distance)
  335. {
  336. distance = distancemeta;
  337. cadedate = metadata;
  338. }
  339. }
  340. }
  341. }
  342. if(cadedate==nil)
  343. return;
  344. AVMetadataMachineReadableCodeObject *transformed = (AVMetadataMachineReadableCodeObject *)[_previewLayer transformedMetadataObjectForMetadataObject:cadedate];
  345. // Update the frame on the _boundingBox view, and show it
  346. // CGRect rt = transformed.bounds;
  347. _boundingBox.frame = transformed.bounds;
  348. _boundingBox.hidden = NO;
  349. // Now convert the corners array into CGPoints in the coordinate system
  350. // of the bounding box itself
  351. // NSArray * corners = transformed.corners;
  352. NSArray *translatedCorners = [self translatePoints:transformed.corners
  353. fromView:self.view
  354. toView:_boundingBox];
  355. // Set the corners array
  356. _boundingBox.corners = translatedCorners;
  357. // Update the view with the decoded text
  358. _decodedMessage.text = [transformed stringValue];
  359. // Start the timer which will hide the overlay
  360. [self startOverlayHideTimer];
  361. [self playSound];
  362. self.handelOutput = false;
  363. [self StopScan];
  364. self.scan_val = [transformed stringValue];
  365. [self dismissViewControllerAnimated:false completion:^{
  366. if(self.returnCode)
  367. self.returnCode(self.scan_val);
  368. }];
  369. // switch (self.target) {
  370. // case SCANNER_TARGET_DETAIL:
  371. // {
  372. // DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  373. // // dvc
  374. //
  375. //
  376. // dvc.use_model_name = true;
  377. // dvc.model_name=[transformed stringValue];
  378. // dvc.category_id=nil;
  379. // dvc.ispush = true;
  380. //
  381. // [dvc reload];
  382. // [self.navigationController pushViewController:dvc animated:true];
  383. // }
  384. // break;
  385. // case SCANNER_TARGET_CART:
  386. // {
  387. //
  388. //
  389. // [CartUtils add_to_cart:self selectorholder:self selector:@selector(addtocart)];
  390. //// return;
  391. //// [self add_toCart];
  392. // // DetailViewController* dvc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailViewController" ];
  393. // // // dvc
  394. // //
  395. // //
  396. // // dvc.use_model_name = true;
  397. // // dvc.model_name=[transformed stringValue];
  398. // // dvc.category_id=nil;
  399. // // dvc.ispush = true;
  400. // //
  401. // // [dvc reload];
  402. // // [self.navigationController pushViewController:dvc animated:true];
  403. // }
  404. // break;
  405. // default:
  406. // break;
  407. // }
  408. }
  409. //-(void)add_toCart
  410. //{
  411. //
  412. //
  413. //
  414. // UIApplication * app = [UIApplication sharedApplication];
  415. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  416. // MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  417. // if(appDelegate.bLogin==false)
  418. // {
  419. // LoginViewController * loginvc =[ self.storyboard instantiateViewControllerWithIdentifier:@"LoginViewController"];
  420. //
  421. //
  422. // loginvc.returnValue = ^(bool blogin){
  423. //
  424. //
  425. //
  426. //
  427. //
  428. // if(blogin)
  429. // {
  430. // if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE*/ true)
  431. // {
  432. // [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:false];
  433. // [main_vc checklogin:false];
  434. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"Do you want to add to pending a order or a new order", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
  435. //
  436. //
  437. //
  438. // // alert.
  439. // [alert show];
  440. // }
  441. // else
  442. // {
  443. // [main_vc checklogin:true];
  444. // }
  445. // }
  446. //
  447. //
  448. //
  449. // };
  450. //
  451. // UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:loginvc] ;
  452. //
  453. //
  454. //
  455. //
  456. //
  457. // // [self hackModalSheetSize:CGSizeMake(450, 200) ofVC:navi];
  458. //
  459. // navi.modalPresentationStyle = UIModalTransitionStyleCrossDissolve;//有三种状态,自己看看是哪种
  460. // [self presentViewController:navi animated:YES completion:^{
  461. //
  462. // // navi.view.superview.bounds = CGRectMake(0, 0, 480, 320);
  463. //
  464. // DebugLog(@"LoginViewController present.........");
  465. //
  466. // // self.btop = false;
  467. // // <#code#>
  468. // }];
  469. // }
  470. // else
  471. // {
  472. //
  473. //
  474. // if(/*appDelegate.user_type==USER_ROLE_EMPLOYEE&&/*appDelegate.contact_id==nil&&*/appDelegate.order_code==nil)
  475. // {
  476. // [main_vc checklogin:false];
  477. //
  478. // if(appDelegate.can_create_order)
  479. // {
  480. // NSString* msg =@"";
  481. // if(appDelegate.contact_id.length>0)
  482. // {
  483. // msg = [msg stringByAppendingString:@"\n\nCustomer:"];
  484. // msg = [msg stringByAppendingString:appDelegate.customerInfo[@"customer_name"]];
  485. //
  486. // }
  487. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:msg delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil),NSLocalizedString(@"Add to new order", nil), nil];
  488. //
  489. // // alert.
  490. // [alert show];
  491. // }
  492. // else
  493. // {
  494. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Add to cart", nil) message:NSLocalizedString(@"", nil) delegate:self cancelButtonTitle:NSLocalizedString(@"Cancel", nil) otherButtonTitles:NSLocalizedString(@"Add to pending order", nil), nil];
  495. //
  496. // // alert.
  497. // [alert show];
  498. // }
  499. // }
  500. // else
  501. // {
  502. //
  503. //
  504. // if(appDelegate.order_code==nil)
  505. // [ self neworder];
  506. // else
  507. // [self addtocart];
  508. //
  509. //
  510. // }
  511. // }
  512. //
  513. //
  514. //
  515. //
  516. //
  517. //
  518. //
  519. //
  520. //}
  521. //-(void) neworder
  522. //{
  523. //
  524. // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait" title:@"Create Order"];
  525. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  526. //
  527. // NSDictionary* return_json = [iSalesNetwork new_Order];
  528. //
  529. // dispatch_async(dispatch_get_main_queue(), ^{
  530. // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  531. //
  532. //
  533. // if([[return_json valueForKey:@"result"] intValue]==2)
  534. // {
  535. // int result=[[return_json valueForKey:@"result"] intValue];
  536. // if(result==2)
  537. // {
  538. // //successed.
  539. //
  540. // NSString* order_code = [return_json valueForKey:@"orderCode"];
  541. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  542. // appDelegate.order_code = order_code;
  543. // appDelegate.order_status = [[return_json valueForKey:@"orderStatus"] intValue];
  544. //
  545. //
  546. // [self addtocart];
  547. //
  548. //
  549. //
  550. // }
  551. // }
  552. // else
  553. // {
  554. //
  555. // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  556. // }
  557. //
  558. //
  559. //
  560. //
  561. // });
  562. // });
  563. //}
  564. //-(void) addtocart
  565. //{
  566. //
  567. //
  568. //
  569. // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  570. //
  571. // NSDictionary* return_json = [iSalesNetwork add_toCart_byName: self.scan_val];
  572. //
  573. // dispatch_async(dispatch_get_main_queue(), ^{
  574. //
  575. //
  576. //
  577. // if([[return_json valueForKey:@"result"] intValue]==2)
  578. // {
  579. //
  580. //
  581. // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  582. //
  583. // [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  584. //
  585. //
  586. //
  587. //
  588. //
  589. // }
  590. // else
  591. // {
  592. //
  593. // [RAUtils message_alert:[return_json valueForKey:@"err_msg"] title:@"Add To Cart" controller:self] ;
  594. // }
  595. //
  596. //
  597. //
  598. //
  599. // });
  600. // });
  601. //
  602. //
  603. //}
  604. //- (IBAction)TargetButtonClick:(id)sender {
  605. //
  606. // UIAlertController *alertControl = [UIAlertController alertControllerWithTitle:@"Change scanner target to" message:nil preferredStyle:UIAlertControllerStyleAlert];
  607. // //block代码块取代了delegate
  608. //
  609. //
  610. //
  611. // UIAlertAction *actionOne = [UIAlertAction actionWithTitle:@"Model Detail" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  612. //
  613. // [self.targetButton setTitle:@"Target: Model Detail" forState:UIControlStateNormal];
  614. //
  615. // self.target = SCANNER_TARGET_DETAIL;
  616. // // UIAlertView * waitalert = [RAUtils waiting_alert:@"Please wait..." title:@"Remove Models From Cart"];
  617. // // dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  618. // //
  619. // // NSDictionary* cart_json = [iSalesNetwork cart_remove:ids];
  620. // //
  621. // // dispatch_async(dispatch_get_main_queue(), ^{
  622. // //
  623. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  624. // //
  625. // // if([[cart_json valueForKey:@"result"] intValue]==2)
  626. // // {
  627. // //
  628. // // [self end_edit];
  629. // // AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  630. // // [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:true];
  631. // // [((MainViewController*)appDelegate.main_vc) reloadCategory:true immediately:true];
  632. // // }
  633. // // else
  634. // // {
  635. // // [RAUtils message_alert:[cart_json valueForKey:@"err_msg"] title:@"Delete Model" controller:self] ;
  636. // // }
  637. // //
  638. // //
  639. // //
  640. // // });
  641. // // });
  642. //
  643. //
  644. // }];
  645. //
  646. // UIAlertAction *alertthree = [UIAlertAction actionWithTitle:@"Cart" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  647. //
  648. //
  649. // [self.targetButton setTitle:@"Target: Cart" forState:UIControlStateNormal];
  650. // self.target = SCANNER_TARGET_CART;
  651. //
  652. // DebugLog(@"No");
  653. // }];
  654. // [alertControl addAction:actionOne];
  655. //
  656. // [alertControl addAction:alertthree];
  657. //
  658. // //UIAlertControllerStyle类型为UIAlertControllerStyleAlert可以添加addTextFieldWithConfigurationHandler:^(UITextField *textField)
  659. //
  660. //
  661. // [self presentViewController:alertControl animated:YES completion:nil];
  662. //
  663. //
  664. //
  665. //
  666. //
  667. //}
  668. - (IBAction)ScanButtonClick:(id)sender {
  669. self.scanButton.backgroundColor = [UIColor greenColor];
  670. [self.scanButton setTitle:@"Scanning" forState:UIControlStateNormal];
  671. // self.scanButton.layer.borderWidth = 1;
  672. self.handelOutput = true;
  673. // if (self.Scannerdelegate && [self.Scannerdelegate respondsToSelector:@selector(BeginScan:)]) {
  674. // [self.Scannerdelegate BeginScan:true];
  675. // }
  676. }
  677. -(void) StopScan
  678. {
  679. self.scanButton.backgroundColor = [UIColor redColor];
  680. [self.scanButton setTitle:@"Tap" forState:UIControlStateNormal];
  681. }
  682. #pragma mark - Utility Methods
  683. - (void)startOverlayHideTimer
  684. {
  685. // Cancel it if we're already running
  686. if(_boxHideTimer) {
  687. [_boxHideTimer invalidate];
  688. }
  689. // Restart it to hide the overlay when it fires
  690. _boxHideTimer = [NSTimer scheduledTimerWithTimeInterval:0.2
  691. target:self
  692. selector:@selector(removeBoundingBox:)
  693. userInfo:nil
  694. repeats:NO];
  695. }
  696. - (void)removeBoundingBox:(id)sender
  697. {
  698. // Hide the box and remove the decoded text
  699. _boundingBox.hidden = YES;
  700. // _decodedMessage.text = @"";
  701. }
  702. - (NSArray *)translatePoints:(NSArray *)points fromView:(UIView *)fromView toView:(UIView *)toView
  703. {
  704. NSMutableArray *translatedPoints = [NSMutableArray new];
  705. // The points are provided in a dictionary with keys X and Y
  706. for (NSDictionary *point in points) {
  707. // Let's turn them into CGPoints
  708. CGPoint pointValue = CGPointMake([point[@"X"] floatValue], [point[@"Y"] floatValue]);
  709. // Now translate from one view to the other
  710. CGPoint translatedPoint = [fromView convertPoint:pointValue toView:toView];
  711. // Box them up and add to the array
  712. [translatedPoints addObject:[NSValue valueWithCGPoint:translatedPoint]];
  713. }
  714. return [translatedPoints copy];
  715. }
  716. //#pragma mark - UIAlertViewDelegate
  717. //// Called when a button is clicked. The view will be automatically dismissed after this call returns
  718. //- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
  719. //{
  720. // UIApplication * app = [UIApplication sharedApplication];
  721. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  722. //
  723. //
  724. // // int count=[self.quantity_text.text intValue];
  725. //
  726. // MainViewController* main_vc=(MainViewController*)appDelegate.main_vc;
  727. // if(buttonIndex==alertView.cancelButtonIndex)
  728. // {
  729. //
  730. //
  731. //
  732. // }
  733. // else if(buttonIndex==1)
  734. // {
  735. // //open exist
  736. // OrderListViewController* ovc =[ self.storyboard instantiateViewControllerWithIdentifier:@"OrderListViewController"];
  737. // ovc.showNavibar = true;
  738. // ovc.selectOrder = ^(NSMutableDictionary* order_detail){
  739. // if(appDelegate.order_code==nil)
  740. // {
  741. // [self neworder];
  742. // }
  743. // else
  744. // {
  745. // [((MainViewController*)appDelegate.main_vc) reloadCart:true immediately:false];
  746. //
  747. //
  748. // [self addtocart];
  749. // [main_vc checklogin:true];
  750. //
  751. //
  752. // }
  753. //
  754. // };
  755. // ovc.init_style = OL_OPEN;
  756. // ovc.onCancel = ^(){
  757. //
  758. // [main_vc checklogin:true];
  759. //
  760. // };
  761. //
  762. // [self.navigationController pushViewController:ovc animated:true];
  763. // }
  764. // else
  765. // {
  766. // //create new;
  767. // if(appDelegate.customerInfo==nil)// select contact if current contact not exist
  768. // {
  769. //
  770. //
  771. // ContactListViewController* cvc = [self.storyboard instantiateViewControllerWithIdentifier:@"ContactListViewController" ];
  772. // cvc.showNavibar = true;
  773. // cvc.contact_type = @"Sales_Order_Customer";
  774. // cvc.returnValue = ^(NSMutableDictionary* value,NSIndexPath* source){
  775. //
  776. // appDelegate.contact_id=[value valueForKey:@"customer_cid"];
  777. // appDelegate.customerInfo = value;
  778. //
  779. //
  780. // if(appDelegate.order_code==nil)
  781. // [self neworder];
  782. //
  783. // [main_vc checklogin:true];
  784. // // [self handle_action_return:value indexPath:indexPath action:ACTION_FILL_SECTION];
  785. //
  786. // //
  787. // // if(self.returnValue)
  788. // // self.returnValue(value);
  789. // };
  790. //
  791. // cvc.onCancel = ^(){
  792. //
  793. // UIViewController *vc= [RAUtils getViewController:self];
  794. // [RAUtils message_alert:@"Cannot create order without cursomer infomation." title:@"New Order" controller:vc];
  795. //
  796. // };
  797. // cvc.onReset = ^(){
  798. // [main_vc checklogin:true];
  799. // };
  800. //
  801. // [self.navigationController pushViewController:cvc animated:true];
  802. // }
  803. // else
  804. // {
  805. // [self neworder];
  806. // }
  807. //
  808. //
  809. // }
  810. //}
  811. @end