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