ImageUploadViewController.m 16 KB

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