ImageUploadViewController.m 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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. if(appDelegate.offline_mode)
  155. {
  156. NSData *data = [OLDataProvider offline_saveBusinesscard:UIImagePNGRepresentation(self.imgview.image)];;
  157. // 再将NSData转为字符串
  158. NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  159. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  160. DebugLog(@"data string: %@",jsonStr);
  161. NSError *error=nil;
  162. NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&error];
  163. if([[json valueForKey:@"result"] intValue]==2)
  164. {
  165. NSString* img_url_down = json[@"img_url_aname"];
  166. NSString* img_url_up = json[@"img_url"];
  167. if(self.returnValue)
  168. self.returnValue(img_url_down,img_url_up,self.imgview.image);
  169. [self.navigationController popViewControllerAnimated:false];
  170. }
  171. else
  172. {
  173. [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  174. }
  175. }
  176. else
  177. {
  178. // UIAlertView * waitalert = [[UIAlertView alloc] initWithTitle:@"wait" message:@"uploading" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
  179. // [waitalert show];
  180. [ERPUtils googleAnalyticsSendRequestString:nil WithScreen:ScreenCodeUploadImage Action:nil Extra:nil];
  181. NSData *imageData = UIImagePNGRepresentation(self.imgview.image);
  182. NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
  183. if(appDelegate.user!=nil)
  184. [params setValue:appDelegate.user forKey:@"user"];
  185. if(appDelegate.password!=nil)
  186. [params setValue:appDelegate.password forKey:@"password"];
  187. // AFHTTPRequestSerializer* serializer=[AFHTTPRequestSerializer serializer] ;
  188. //
  189. // NSMutableURLRequest *request = [serializer multipartFormRequestWithMethod:@"POST" URLString:URL_UPLOAD_IMG parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  190. // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test.jpg" mimeType:@"image/png"];
  191. // } error:nil];
  192. //
  193. //
  194. // // NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:WEBSERVICE_URL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
  195. // // [formData appendPartWithFileData:imageData name:@"upfile" fileName:@"test" mimeType:@"image/png"];
  196. // // } error:nil];
  197. // //
  198. // AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
  199. //
  200. //
  201. //
  202. // //manager.responseSerializer.acceptableContentTypes = [self.operationManager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
  203. //
  204. //
  205. //
  206. // //
  207. // NSProgress *progress = nil;
  208. //
  209. // NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithStreamedRequest:request progress:&progress completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
  210. //
  211. // // [progress removeObserver:self forKeyPath:@"fractionCompleted"];
  212. //
  213. //
  214. //
  215. //
  216. // if (error) {
  217. //
  218. // NSString* err_msg = [error localizedDescription];
  219. // DebugLog(@"%@",err_msg);// [self.view updateWithMessage:[NSString stringWithFormat:@"Error : %@!", error.debugDescription]];
  220. //
  221. //
  222. // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  223. //
  224. // DebugLog(@"data string: %@",str);
  225. // [RAUtils message_alert:@"Can not connect to server please try again." title:@"Upload Image" controller:self] ;
  226. //
  227. // } else {
  228. // DebugLog(@"response ");
  229. //
  230. //
  231. //
  232. // NSData *data = [NSJSONSerialization dataWithJSONObject:(NSDictionary*)responseObject options:kNilOptions error:nil];
  233. //
  234. // // 再将NSData转为字符串
  235. // NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  236. //
  237. // // NSMutableString *str = [[NSMutableString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  238. //
  239. // DebugLog(@"data string: %@",jsonStr);
  240. //
  241. // NSDictionary* json = responseObject;
  242. //
  243. //
  244. // if([[json valueForKey:@"result"] intValue]==2)
  245. // {
  246. // NSString* img_url_down = json[@"img_url_aname"];
  247. // NSString* img_url_up = json[@"img_url"];
  248. //
  249. // if(self.returnValue)
  250. // self.returnValue(img_url_down,img_url_up,self.imgview.image);
  251. //
  252. // [self.navigationController popViewControllerAnimated:false];
  253. // }
  254. // else
  255. // {
  256. // [RAUtils message_alert:[json valueForKey:@"err_msg"] title:@"Upload Image" controller:self] ;
  257. // }
  258. //
  259. //
  260. // }
  261. // // [waitalert dismissWithClickedButtonIndex:0 animated:FALSE];
  262. // }];
  263. //
  264. //
  265. //
  266. //
  267. // [self.uploadProgress setProgressWithUploadProgressOfTask:uploadTask animated:true];
  268. // //
  269. //
  270. //
  271. //
  272. //
  273. //
  274. //
  275. // [uploadTask resume];
  276. __weak typeof(self) weakSelf = self;
  277. [NetworkUtils upload:imageData FileName:@"test.jpg" Params:params ToHost:URL_UPLOAD_IMG Result:^(NSMutableDictionary *result) {
  278. dispatch_async(dispatch_get_main_queue(), ^{
  279. if([[result valueForKey:@"result"] intValue]==2)
  280. {
  281. NSString* img_url_down = result[@"img_url_aname"];
  282. NSString* img_url_up = result[@"img_url"];
  283. if(weakSelf.returnValue)
  284. weakSelf.returnValue(img_url_down,img_url_up,self.imgview.image);
  285. [weakSelf.navigationController popViewControllerAnimated:false];
  286. }
  287. else
  288. {
  289. [RAUtils message_alert:[result valueForKey:@"err_msg"] title:@"Upload Image" controller:weakSelf] ;
  290. }
  291. });
  292. } Progress:^(NSURLSessionTask *task, double progress) {
  293. dispatch_async(dispatch_get_main_queue(), ^{
  294. [weakSelf.uploadProgress setProgress:progress animated:YES];
  295. });
  296. } DecryptHandler:nil];
  297. }
  298. }
  299. #pragma mark - imagePicker delegate
  300. - (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
  301. self.dirty = true;
  302. /*-------------------------------相机拍照--------------------------------------*/
  303. if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
  304. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  305. image=[RAUtils img_compress:image kbsize:500];
  306. self.imgview.image = image;
  307. [picker dismissViewControllerAnimated:YES completion:^{
  308. }];
  309. } else if (picker .sourceType == UIImagePickerControllerSourceTypePhotoLibrary) {
  310. /**
  311. * UIImagePickerControllerEditedImage 取得的是被编辑过的图片,需要allowsEditing设置为YES
  312. * UIImagePickerControllerOriginalImage 取得的是相册中原始图片
  313. */
  314. UIImage * image = [info objectForKey:UIImagePickerControllerEditedImage];
  315. image=[RAUtils img_compress:image kbsize:500];
  316. self.imgview.image = image;
  317. [picker dismissViewControllerAnimated:YES completion:nil];
  318. }
  319. }
  320. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
  321. [picker dismissViewControllerAnimated:YES completion:nil];
  322. // [picker presentViewController:cameraPicker animated:YES completion:nil];
  323. DebugLog(@"%s",__FUNCTION__);
  324. }
  325. /*
  326. #pragma mark - Navigation
  327. // In a storyboard-based application, you will often want to do a little preparation before navigation
  328. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  329. // Get the new view controller using [segue destinationViewController].
  330. // Pass the selected object to the new view controller.
  331. }
  332. */
  333. @end