SocialPublishViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. //
  2. // SocialPublishViewController.m
  3. // NIMDemo
  4. //
  5. // Created by Fenix Wang on 2017/6/20.
  6. // Copyright © 2017年 Netease. All rights reserved.
  7. //
  8. #import "SocialPublishViewController.h"
  9. #import "UIView+NTES.h"
  10. #import "UIView+Toast.h"
  11. #import "User.h"
  12. #import "NIMKitMediaFetcher.h"
  13. #import "SVProgressHUD.h"
  14. #import "UIImage+NIM.h"
  15. #import "AFNetworking/AFNetworking.h"
  16. #import "LocationManager.h"
  17. #import "HttpRequest.h"
  18. @interface SocialPublishViewController ()<UITextViewDelegate, LocationDelegate>
  19. @property (nonatomic, strong) LocationManager *locationManager;
  20. @property (nonatomic, assign) double longitude;
  21. @property (nonatomic, assign) double latitude;
  22. @property (nonatomic, strong) UITextView *msgTxtView;
  23. @property (nonatomic, strong) UILabel *msgReplaceHolder;
  24. @property (nonatomic, strong) UILabel *locationLabel;
  25. @property (nonatomic, strong) UILabel *picLabel;
  26. @property (nonatomic, strong) NSMutableArray *picArr;
  27. @property (nonatomic, strong) NSMutableArray *picDataArr;
  28. @property (nonatomic, assign) int picUploadIndex;
  29. @property (nonatomic, strong) UIView *picContainer;
  30. @property (nonatomic, strong) UIButton *picAddBtn;
  31. @property (nonatomic, strong) NIMKitMediaFetcher *mediaFetcher;
  32. @end
  33. int maxCountPictures = 9;
  34. CGFloat picPadding = 5;
  35. int picColumns = 5;
  36. @implementation SocialPublishViewController
  37. - (void)viewDidLoad {
  38. [super viewDidLoad];
  39. // Do any additional setup after loading the view.
  40. self.view.backgroundColor = UIColor.whiteColor;
  41. _picArr = [[NSMutableArray alloc] init];
  42. _picDataArr = [[NSMutableArray alloc] init];
  43. UINavigationItem *navItem = self.navigationItem;
  44. [navItem setTitle:@"发布"];
  45. CGFloat navBottom = self.navigationController.navigationBar.bottom;
  46. _msgTxtView = [[UITextView alloc] initWithFrame:CGRectMake(15, navBottom + 10, self.view.width-30, 100)];
  47. [_msgTxtView setText:@""];
  48. _msgTxtView.delegate = self;
  49. _msgTxtView.font = [UIFont systemFontOfSize:15];
  50. _msgTxtView.backgroundColor = UIColor.clearColor;
  51. _msgReplaceHolder = [[UILabel alloc] initWithFrame:CGRectMake(15, navBottom + 10, self.view.width-30, 30)];
  52. _msgReplaceHolder.textColor = UIColor.lightGrayColor;
  53. _msgReplaceHolder.text = @"你想说点什么";
  54. _msgReplaceHolder.font = [UIFont systemFontOfSize:15];
  55. [self.view addSubview:_msgReplaceHolder];
  56. [self.view addSubview:_msgTxtView];
  57. UIView *locationView = [[UIView alloc] initWithFrame:CGRectMake(15, _msgTxtView.bottom + 10, 100, 30)];
  58. locationView.layer.cornerRadius = 15;
  59. locationView.backgroundColor = [UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1];
  60. UIImageView *locationIcon = [[UIImageView alloc] initWithFrame:CGRectMake(10, 4, 18, 22)];
  61. [locationIcon setImage:[UIImage imageNamed:@"朋友圈发布_03"]];
  62. [locationView addSubview:locationIcon];
  63. _locationLabel = [[UILabel alloc] initWithFrame:CGRectMake(locationIcon.right+5, 0, 0, 30)];
  64. [_locationLabel setText:[User sharedInfo].district ? [NSString stringWithFormat:@"%@%@", [User sharedInfo].city, [User sharedInfo].district] : @""];
  65. _locationLabel.textColor = UIColor.grayColor;
  66. _locationLabel.font = [UIFont systemFontOfSize:15];
  67. [_locationLabel sizeToFit];
  68. _locationLabel.top = (30 - _locationLabel.height)/2;
  69. [locationView addSubview:_locationLabel];
  70. locationView.width = _locationLabel.right + 10;
  71. [self.view addSubview:locationView];
  72. _picLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, locationView.bottom + 10, 150, 30)];
  73. _picLabel.textColor = UIColor.lightGrayColor;
  74. [self.view addSubview:_picLabel];
  75. [self updatePictureTip];
  76. float picSize = (self.view.width - 20 - picPadding * (picColumns - 1)) / picColumns;
  77. _picContainer = [[UIView alloc] initWithFrame:CGRectMake(10, _picLabel.bottom+10, self.view.width - 20, picSize * 2 + picPadding)];
  78. [self.view addSubview:_picContainer];
  79. _picAddBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, picSize, picSize)];
  80. [_picAddBtn setImage:[UIImage imageNamed:@"朋友圈发布_07"] forState:UIControlStateNormal];
  81. [_picAddBtn addTarget:self action:@selector(onTouchAddPic:) forControlEvents:UIControlEventTouchUpInside];
  82. [_picContainer addSubview:_picAddBtn];
  83. UIButton *publishBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, _picContainer.bottom+20, self.view.width - 30, 50)];
  84. [publishBtn setTitle:@"发布" forState:UIControlStateNormal];
  85. [publishBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
  86. publishBtn.backgroundColor = User.orangeColor;
  87. publishBtn.layer.cornerRadius = 5;
  88. [publishBtn addTarget:self action:@selector(onTouchPublish:) forControlEvents:UIControlEventTouchUpInside];
  89. [self.view addSubview:publishBtn];
  90. _locationManager = [LocationManager sharedManager];
  91. _locationManager.delegate = self;
  92. [_locationManager startUpdate];
  93. }
  94. - (void)didReceiveMemoryWarning {
  95. [super didReceiveMemoryWarning];
  96. // Dispose of any resources that can be recreated.
  97. [_locationManager stopUpdate];
  98. _locationManager.delegate = nil;
  99. }
  100. - (void)viewWillAppear:(BOOL)animated
  101. {
  102. [super viewWillAppear:animated];
  103. }
  104. - (void)coordinateUpdate:(double)longitude latitude:(double)latitude{
  105. self.longitude = longitude;
  106. self.latitude = latitude;
  107. __weak typeof(self) wself = self;
  108. [[HttpRequest shared] location:longitude latitude:latitude success:^(NSString * _Nullable province, NSString * _Nullable city, NSString * _Nullable district, NSString * _Nullable provinceRoomId, NSString * _Nullable cityRoomId, NSString * _Nullable districtRoomId) {
  109. if(city && district && city.length > 0 && district.length > 0)
  110. {
  111. if([city isEqualToString:district])
  112. {
  113. wself.locationLabel.text = district;
  114. }
  115. else
  116. {
  117. wself.locationLabel.text = [NSString stringWithFormat:@"%@%@", city, district];
  118. }
  119. [wself.locationManager stopUpdate];
  120. }
  121. } failure:^{
  122. }];
  123. }
  124. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
  125. {
  126. if (![text isEqualToString:@""])
  127. {
  128. _msgReplaceHolder.hidden = YES;
  129. }
  130. if ([text isEqualToString:@""] && range.location == 0 && range.length == 1)
  131. {
  132. _msgReplaceHolder.hidden = NO;
  133. }
  134. return YES;
  135. }
  136. - (void)updatePictureTip
  137. {
  138. _picLabel.text = [NSString stringWithFormat:@"照片不超过%d张", (int)(maxCountPictures - _picArr.count)];
  139. }
  140. - (void)layoutPictures
  141. {
  142. float picSize = (self.view.width - 20 - picPadding * (picColumns - 1)) / picColumns;
  143. CGFloat startX = 0;
  144. CGFloat startY = 0;
  145. int count = (int)_picArr.count;
  146. int i = 0;
  147. for(i=0; i<count; i++){
  148. startX = (i % picColumns) * (picSize + picPadding);
  149. startY = floorf(i / picColumns);
  150. UIImageView *imgView = nil;
  151. if(_picContainer.subviews.count - 1 <= i){
  152. imgView = [[UIImageView alloc] initWithFrame:CGRectMake(startX, startY, picSize, picSize)];
  153. [_picContainer addSubview:imgView];
  154. }
  155. else{
  156. imgView = [_picContainer.subviews objectAtIndex:i];
  157. imgView.left = startX;
  158. imgView.top = startY;
  159. }
  160. UIImage *img = [_picArr objectAtIndex:i];
  161. [imgView setImage:img];
  162. }
  163. if(count < maxCountPictures)
  164. {
  165. startX = (count % picColumns) * (picSize + picPadding);
  166. startY = floorf(count / picColumns);
  167. _picAddBtn.left = startX;
  168. _picAddBtn.top = startY;
  169. _picAddBtn.hidden = NO;
  170. }
  171. else
  172. {
  173. _picAddBtn.hidden = YES;
  174. }
  175. }
  176. - (void)onTouchAddPic:(int)sender
  177. {
  178. [self showImagePicker:UIImagePickerControllerSourceTypePhotoLibrary];
  179. }
  180. - (NIMKitMediaFetcher *)mediaFetcher
  181. {
  182. if (!_mediaFetcher) {
  183. _mediaFetcher = [[NIMKitMediaFetcher alloc] init];
  184. }
  185. return _mediaFetcher;
  186. }
  187. - (void)showImagePicker:(UIImagePickerControllerSourceType)type{
  188. __weak typeof(self) weakSelf = self;
  189. [self.mediaFetcher fetchPhotoFromLibrary:^(NSArray *images, NSString *path, PHAssetMediaType type) {
  190. int a = 1;
  191. NSLog(@"%d", a);
  192. switch (type) {
  193. case PHAssetMediaTypeImage:
  194. {
  195. for (UIImage *image in images) {
  196. [weakSelf.picArr addObject:image];
  197. }
  198. [weakSelf layoutPictures];
  199. }
  200. break;
  201. case PHAssetMediaTypeVideo:
  202. {
  203. }
  204. break;
  205. default:
  206. return;
  207. }
  208. }];
  209. }
  210. - (void)onTouchPublish:(int)sender{
  211. [SVProgressHUD show];
  212. [self uploadPicture];
  213. }
  214. - (void)uploadPicture{
  215. if(_msgTxtView.text.length == 0 && _picArr.count == 0)
  216. {
  217. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"你还什么都没说呢" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
  218. [alert show];
  219. return;
  220. }
  221. if(_picUploadIndex >= _picArr.count)
  222. {
  223. [self publish];
  224. return;
  225. }
  226. UIImage *image = [_picArr objectAtIndex:_picUploadIndex];
  227. NSString *userId = [NSString stringWithFormat:@"%d", [User sharedInfo].userId];
  228. NSDictionary *dict = @{@"user_id":userId};
  229. NSString *urlString = @"http://whosay.dashgame.com/index.php?m=who&c=social&a=upload";
  230. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  231. manager.responseSerializer = [AFJSONResponseSerializer serializer];
  232. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/html", nil];
  233. [manager POST:urlString parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
  234. NSData *data = UIImageJPEGRepresentation(image, 1);
  235. [formData appendPartWithFileData:data name:@"upload" fileName:[NSString stringWithFormat:@"image_%d.jpg", _picUploadIndex] mimeType:@"image/jpg"];
  236. } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
  237. //NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
  238. //NSLog(@"请求成功,服务器返回的信息%@", string);
  239. NSLog(@"请求成功,服务器返回的信息%@", responseObject);
  240. int code = [[responseObject objectForKey:@"c"] intValue];
  241. if(code == 0)
  242. {
  243. NSDictionary *data = [responseObject objectForKey:@"d"];
  244. NSString *aid = [data objectForKey:@"aid"];
  245. if(_picUploadIndex >= _picDataArr.count)
  246. {
  247. [_picDataArr addObject:aid];
  248. }
  249. else
  250. {
  251. [_picDataArr setObject:aid atIndexedSubscript:_picUploadIndex];
  252. }
  253. _picUploadIndex++;
  254. [self uploadPicture];
  255. }
  256. else{
  257. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:[responseObject objectForKey:@"d"] delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"重试", nil];
  258. [alert show];
  259. }
  260. } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
  261. NSLog(@"请求失败,服务器返回的错误信息%@",error);
  262. UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"上传图片失败" delegate:self cancelButtonTitle:@"放弃" otherButtonTitles:@"重试", nil];
  263. [alert show];
  264. }];
  265. }
  266. - (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
  267. switch (buttonIndex) {
  268. case 0:
  269. [self.navigationController popViewControllerAnimated:YES];
  270. break;
  271. case 1:
  272. [self uploadPicture];
  273. break;
  274. default:
  275. break;
  276. }
  277. }
  278. - (void)publish
  279. {
  280. User *user = [User sharedInfo];
  281. NSString *userId = [NSString stringWithFormat:@"%d", user.userId];
  282. // NSMutableDictionary *parameters = @{@"id":userId,
  283. // @"local":_locationLabel.text,
  284. // @"msg":_msgTxtView.text,
  285. // @"pic":_picDataArr,
  286. // };
  287. NSString *local = _locationLabel.text ? _locationLabel.text : @"";
  288. NSString *msg = _msgTxtView.text ? _msgTxtView.text : @"";
  289. NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
  290. [parameters setObject:userId forKey:@"id"];
  291. [parameters setObject:local forKey:@"local"];
  292. [parameters setObject:msg forKey:@"msg"];
  293. [parameters setObject:_picDataArr forKey:@"pic"];
  294. [parameters setObject:[NSString stringWithFormat:@"%F", _longitude] forKey:@"longitude"];
  295. [parameters setObject:[NSString stringWithFormat:@"%F", _latitude] forKey:@"latitude"];
  296. NSString *urlString = @"http://whosay.dashgame.com/index.php?m=who&c=social&a=publish";
  297. //请求的managers
  298. AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
  299. manager.responseSerializer = [AFJSONResponseSerializer new];
  300. manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
  301. //请求的方式:POST
  302. NSLog(@"%@", parameters);
  303. [manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
  304. [SVProgressHUD dismiss];
  305. NSLog(@"请求成功,服务器返回的信息%@", responseObject);
  306. NSDictionary * dic = responseObject;
  307. int code = [[dic valueForKey:@"c"] intValue];
  308. if(code == 0){
  309. NSDictionary *data = (NSDictionary *)[dic objectForKey:@"d"];
  310. NSLog(@"Json解析结果 = %d %@", code, data);
  311. [self.view makeToast:@"发布成功" duration:2.0 position:CSToastPositionCenter];
  312. [self.navigationController popViewControllerAnimated:YES];
  313. [User sharedInfo].hasNewSocial = YES;
  314. }
  315. else{
  316. [self.view makeToast:@"发布失败" duration:2.0 position:CSToastPositionCenter];
  317. }
  318. } failure:^(NSURLSessionDataTask *task, NSError * error) {
  319. [SVProgressHUD dismiss];
  320. NSLog(@"请求失败,服务器返回的错误信息%@",error);
  321. [self.view makeToast:@"发布失败" duration:2.0 position:CSToastPositionCenter];
  322. }];
  323. }
  324. @end