ImageUploadViewController.m 15 KB

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