ImageUploadViewController.m 15 KB

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