ImageUploadViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. //
  2. // ImageUploadViewController.m
  3. // RedAnt ERP Mobile
  4. //
  5. // Created by Ray on 11/4/15.
  6. // Copyright © 2015 United Software Applications, Inc. All rights reserved.
  7. //
  8. #import "ImageUploadViewController.h"
  9. //#import "UIProgressView+AFNetworking.h"
  10. //#import "AFHTTPSessionManager.h"
  11. #import "config.h"
  12. #import "RAUtils.h"
  13. #import "AppDelegate.h"
  14. #ifdef OFFLINE_MODE
  15. #import "OLDataProvider.h"
  16. #endif
  17. #ifdef GOOGLE_ANALYTICS
  18. #import "ERPUtils.h"
  19. #endif
  20. //#import "iSalesNetwork.h"
  21. #import "NetworkUtils.h"
  22. //#import "UIAlertView+AFNetworking.h"
  23. #define TEST_URL @"http://192.168.1.3:8080/ios_server/ul.jsp"
  24. @interface ImageUploadViewController ()
  25. @end
  26. @implementation ImageUploadViewController
  27. //-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
  28. //{
  29. //// UIApplication * app = [UIApplication sharedApplication];
  30. //// AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  31. //// [appDelegate didRotated];
  32. //
  33. // // [CATransaction begin];
  34. // // [CATransaction setAnimationDuration:0.5];
  35. // // [CATransaction setAnimationTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
  36. // // // [self updatePreviewLayerForOrientation:toInterfaceOrientation];
  37. // // _previewLayer.position = CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect));
  38. // //
  39. // // // self.backgroundView.highLightRect = CGRectInset(self.focusZone.frame,6,6);
  40. // // _previewLayer.bounds = rect;
  41. // //
  42. // // UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  43. // // switch (orientation) {
  44. // //
  45. // //
  46. // //
  47. // // case UIInterfaceOrientationPortrait:
  48. // // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(0)];
  49. // //
  50. // // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortrait;
  51. // // break;
  52. // // case UIInterfaceOrientationPortraitUpsideDown:
  53. // // //[_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI)];
  54. // // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationPortraitUpsideDown;
  55. // // break;
  56. // // case UIInterfaceOrientationLandscapeLeft:
  57. // // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(M_PI/2)];
  58. // // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeLeft;
  59. // // break;
  60. // // case UIInterfaceOrientationLandscapeRight:
  61. // // // [_previewLayer setAffineTransform:CGAffineTransformMakeRotation(-M_PI/2)];
  62. // // _previewLayer.connection.videoOrientation=AVCaptureVideoOrientationLandscapeRight;
  63. // // break;
  64. // // default:
  65. // // break;
  66. // // }
  67. // // [CATransaction commit];
  68. //
  69. // // 2018.12.28 iPad Pro 11-inch位置不正确
  70. //// NSTimeInterval animationDuration = 0.30f;
  71. //// [UIView beginAnimations:nil context:nil];
  72. //// [UIView setAnimationDuration:animationDuration];
  73. ////
  74. //// UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  75. //// if (UIInterfaceOrientationIsLandscape(orientation))
  76. //// {
  77. ////
  78. ////
  79. //// self.buttonAlbum.frame = CGRectMake(942,120,48,48);
  80. //// self.buttonCamera.frame = CGRectMake(942,200,48,48);
  81. //// self.buttonUpload.frame = CGRectMake(942,363,48,48);
  82. //// // @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
  83. //// // @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
  84. //// // @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
  85. //// }
  86. //// else
  87. //// {
  88. //// self.buttonAlbum.frame = CGRectMake(82,918,48,48);
  89. //// self.buttonCamera.frame = CGRectMake(173,918,48,48);
  90. //// self.buttonUpload.frame = CGRectMake(635,918,48,48);
  91. ////
  92. //// }
  93. ////
  94. //// [UIView commitAnimations];
  95. //
  96. //
  97. //
  98. //
  99. //
  100. //
  101. //}
  102. - (void)viewDidLoad {
  103. [super viewDidLoad];
  104. UIBarButtonItem *closeButton = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAutomatic]
  105. style:UIBarButtonItemStylePlain
  106. target:self
  107. action:@selector( onBackClick:)];
  108. self.navigationItem.leftBarButtonItem = closeButton;
  109. self.imgview.image = self.img;
  110. // UIApplication * app = [UIApplication sharedApplication];
  111. // AppDelegate *appDelegate = (AppDelegate *)[app delegate];
  112. // [appDelegate didRotated];
  113. // 2018.12.28 iPad Pro 11-inch位置不正确
  114. // NSTimeInterval animationDuration = 0.30f;
  115. // [UIView beginAnimations:nil context:nil];
  116. // [UIView setAnimationDuration:animationDuration];
  117. //
  118. // UIInterfaceOrientation orientation = [[UIApplication sharedApplication]statusBarOrientation];
  119. // if (UIInterfaceOrientationIsLandscape(orientation))
  120. // {
  121. //
  122. //
  123. // self.buttonAlbum.frame = CGRectMake(942,120,48,48);
  124. // self.buttonCamera.frame = CGRectMake(942,200,48,48);
  125. // self.buttonUpload.frame = CGRectMake(942,363,48,48);
  126. // // @property (strong, nonatomic) IBOutlet UIButton *buttonAlbum;
  127. // // @property (strong, nonatomic) IBOutlet UIButton *buttonCamera;
  128. // // @property (strong, nonatomic) IBOutlet UIButton *buttonUpload;
  129. // }
  130. // else
  131. // {
  132. // self.buttonAlbum.frame = CGRectMake(82,918,48,48);
  133. // self.buttonCamera.frame = CGRectMake(173,918,48,48);
  134. // self.buttonUpload.frame = CGRectMake(635,918,48,48);
  135. //
  136. // }
  137. //
  138. // [UIView commitAnimations];
  139. // Do any additional setup after loading the view.
  140. }
  141. - (void)onBackClick:(UIButton *)sender {
  142. [self.navigationController popViewControllerAnimated:FALSE];
  143. }
  144. - (void)didReceiveMemoryWarning {
  145. [super didReceiveMemoryWarning];
  146. // Dispose of any resources that can be recreated.
  147. }
  148. - (IBAction)onClickAlbum:(id)sender {
  149. NSUInteger sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
  150. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  151. imagePickerController.delegate = self;
  152. imagePickerController.allowsEditing = YES;
  153. imagePickerController.sourceType = sourceType;
  154. [self presentViewController:imagePickerController animated:YES completion:^{}];
  155. }
  156. - (IBAction)onClickCamera:(id)sender {
  157. if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
  158. {
  159. return;
  160. }
  161. NSUInteger sourceType=UIImagePickerControllerSourceTypeCamera;
  162. UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
  163. imagePickerController.delegate = self;
  164. imagePickerController.allowsEditing = YES;
  165. imagePickerController.sourceType = sourceType;
  166. [self presentViewController:imagePickerController animated:YES completion:^{}];
  167. }
  168. - (IBAction)onClickUpload:(id)sender {
  169. if(self.dirty==false)
  170. {
  171. [RAUtils message_alert:@"Please set a photo first." title:@"Upload" controller:self];
  172. // UIAlertView * alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Upload", nil) message:NSLocalizedString(@"Please set a photo first.", nil) delegate:nil cancelButtonTitle:NSLocalizedString(@"Ok", nil) otherButtonTitles:nil, nil];
  173. //
  174. // // alert.
  175. // [alert show];
  176. return;
  177. }
  178. self.uploadProgress.progress = 0;
  179. AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
  180. #ifdef OFFLINE_MODE
  181. if(appDelegate.offline_mode)
  182. {
  183. NSData *data = [OLDataProvider offline_saveBusinesscard:UIImagePNGRepresentation(self.imgview.image)];;
  184. // 再将NSData转为字符串
  185. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  186. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  187. DebugLog(@"data string: %@",jsonStr);
  188. NSError *error=nil;
  189. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  190. if([[json valueForKey:@"result"] intValue]==2)
  191. {
  192. NSString* img_url_down = json[@"img_url_aname"];
  193. NSString* img_url_up = json[@"img_url"];
  194. if(self.returnValue)
  195. self.returnValue(img_url_down,img_url_up,self.imgview.image);
  196. [self.navigationController popViewControllerAnimated:false];
  197. }
  198. else
  199. {
  200. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  201. }
  202. }
  203. else
  204. #endif
  205. {
  206. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  207. // [waitalert show];
  208. #ifdef GOOGLE_ANALYTICS
  209. NSString *const ScreenCodeUploadImage = @"Upload Image Screen";
  210. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeUploadImage Action:nil Extra:nil];
  211. #endif
  212. NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  213. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  214. if(appDelegate.user!=nil)
  215. [params setValue:appDelegate.user forKey:@"user"];
  216. if(appDelegate.password!=nil)
  217. [params setValue:appDelegate.password forKey:@"password"];
  218. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  219. //
  220. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  221. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
  222. // } error:nil];
  223. //
  224. //
  225. // // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  226. // // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  227. // // } error:nil];
  228. // //
  229. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  230. //
  231. //
  232. //
  233. // //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  234. //
  235. //
  236. //
  237. // //
  238. // NSProgress *progress = nil;
  239. //
  240. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  241. //
  242. // // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  243. //
  244. //
  245. //
  246. //
  247. // if (error) {
  248. //
  249. // NSString* err_msg = [error localizedDescription];
  250. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  251. //
  252. //
  253. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  254. //
  255. // DebugLog(@"data string: %@",str);
  256. // [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  257. //
  258. // } else {
  259. // DebugLog(@"response ");
  260. //
  261. //
  262. //
  263. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  264. //
  265. // // 再将NSData转为字符串
  266. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  267. //
  268. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  269. //
  270. // DebugLog(@"data string: %@",jsonStr);
  271. //
  272. // NSDictionary* json = responseObject;
  273. //
  274. //
  275. // if([[json valueForKey:@"result"] intValue]==2)
  276. // {
  277. // NSString* img_url_down = json[@"img_url_aname"];
  278. // NSString* img_url_up = json[@"img_url"];
  279. //
  280. // if(self.returnValue)
  281. // self.returnValue(img_url_down,img_url_up,self.imgview.image);
  282. //
  283. // [self.navigationController popViewControllerAnimated:false];
  284. // }
  285. // else
  286. // {
  287. // [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  288. // }
  289. //
  290. //
  291. // }
  292. // // [waitalert dismissViewControllerAnimated:YES completion:nil];
  293. // }];
  294. //
  295. //
  296. //
  297. //
  298. // [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  299. // //
  300. //
  301. //
  302. //
  303. //
  304. //
  305. //
  306. // [uploadTask resume];
  307. __weak typeof(self) weakSelf = self;
  308. [NetworkUtils upload:imageData FileName:@"test.jpg" Params:params ToHost:URL_UPLOAD_IMG Result:^(NSMutableDictionary *result) {
  309. dispatch_async(dispatch_get_main_queue(), ^{
  310. if([[result valueForKey:@"result"] intValue]==2)
  311. {
  312. NSString* img_url_down = result[@"img_url_aname"];
  313. NSString* img_url_up = result[@"img_url"];
  314. if(weakSelf.returnValue)
  315. weakSelf.returnValue(img_url_down,img_url_up,self.imgview.image);
  316. [weakSelf.navigationController popViewControllerAnimated:false];
  317. }
  318. else
  319. {
  320. [RAUtils message_alert:[result valueForKey:@"err_msg"] title:@"Upload Image" controller:weakSelf] ;
  321. }
  322. });
  323. } Progress:^(NSURLSessionTask *task, double progress) {
  324. dispatch_async(dispatch_get_main_queue(), ^{
  325. [weakSelf.uploadProgress setProgress:progress animated:YES];
  326. });
  327. } DecryptHandler:nil];
  328. }
  329. }
  330. #pragma mark - imagePicker delegate
  331. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  332. self.dirty = true;
  333. /*-------------------------------相机拍照--------------------------------------*/
  334. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  335. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  336. image=[RAUtils img_compress:image kbsize:500];
  337. self.imgview.image = image;
  338. [picker dismissViewControllerAnimated:YES completion:^{
  339. }];
  340. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  341. /**
  342. * UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
  343. * UIImagePickerControllerOriginalImage 取得的是相册中原始图片
  344. */
  345. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  346. image=[RAUtils img_compress:image kbsize:500];
  347. self.imgview.image = image;
  348. [picker dismissViewControllerAnimated:YES completion:nil];
  349. }
  350. }
  351. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  352. [picker dismissViewControllerAnimated:YES completion:nil];
  353. // [picker presentViewController:cameraPicker animated:YES completion:nil];
  354. DebugLog(@"%s",__FUNCTION__);
  355. }
  356. /*
  357. #pragma mark - Navigation
  358. // In a storyboard-based application, you will often want to do a little preparation before navigation
  359. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  360. // Get the new view controller using [segue destinationViewController].
  361. // Pass the selected object to the new view controller.
  362. }
  363. */
  364. @end