ImageUploadViewController.m 16 KB

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