ChatController.m 96 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567
  1. //
  2. // ChatController.m
  3. // AIIM
  4. //
  5. // Created by gan on 2025/4/6.
  6. //
  7. #import <Foundation/Foundation.h>
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <Photos/Photos.h>
  10. #import <PhotosUI/PhotosUI.h>
  11. #import <MobileCoreServices/MobileCoreServices.h>
  12. #import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
  13. #import "ChatController.h"
  14. #import "FriendController.h"
  15. #import "GroupController.h"
  16. #import "ChatsStore.h"
  17. #import "ChatListStore.h"
  18. #import "FriendNetApi.h"
  19. #import "FileNetApi.h"
  20. #import "GroupNetApi.h"
  21. #import "UserNetApi.h"
  22. #import "GWebSocket.h"
  23. #import "UDManager.h"
  24. #import "CryptoAES.h"
  25. #import "GDBManager.h"
  26. #import "chatpopView.h"
  27. #import "config.h"
  28. #import "JSGController.h"
  29. #import "SDWebImage/SDWebImage.h"
  30. #import "ChatMessageModel.h"
  31. #import "ChatFileModel.h"
  32. #import "AppDelegate.h"
  33. #import "HistoryPreloader.h"
  34. #import "chatCellView.h"
  35. #import "CameraViewController.h"
  36. #import "ForwardViewController.h"
  37. #import "ChatBatchView.h"
  38. #import "ChatQuoteView.h"
  39. #import "ChatAtMemberView.h"
  40. #import "PopupView.h"
  41. #import "MentionTextView.h"
  42. #import "TopPopupView.h"
  43. #import "OSSManager.h"
  44. static const CGFloat kQuoteViewHeight = 46.0f;
  45. @interface ChatController()<UITextViewDelegate,ChatsStoreDelegate,UITableViewDelegate,UITableViewDataSource,chatpopViewDelegate,PHPickerViewControllerDelegate,UINavigationControllerDelegate,UIDocumentPickerDelegate,UIScrollViewDelegate,OSSManagerDelegate>
  46. @property (weak, nonatomic) IBOutlet UILabel *titlelb;
  47. @property (weak, nonatomic) IBOutlet UITableView *_tableView;
  48. @property(nonatomic, strong) MentionTextView *inputView;
  49. //@property(nonatomic, strong) UITextView *inputView;
  50. @property (weak, nonatomic) IBOutlet UIView *bottonView;
  51. @property (weak, nonatomic) IBOutlet UIButton *yuyinctr;
  52. @property (weak, nonatomic) IBOutlet UIButton *fasngBt;
  53. @property (weak, nonatomic) IBOutlet UIButton *gengduoBt;
  54. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *inputViewBottom;
  55. @property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomViewHeight;
  56. @property (nonatomic, strong) HistoryPreloader * preloader;
  57. //录音
  58. @property(nonatomic, strong) UIButton *AVRecordBt;
  59. @property (nonatomic,strong) AVAudioRecorder *recorder;
  60. @property (nonatomic,strong) NSString *AudiofilePath;
  61. @property (nonatomic,strong) NSString *AudiofileName;
  62. @property (nonatomic) NSInteger rcdL;
  63. @property (strong, nonatomic) NSTimer *heatBeat;
  64. @property (nonatomic,strong) AVPlayer *player;
  65. @property (nonatomic) CGFloat keyboardHeight;
  66. @property (nonatomic) BOOL isfriend;
  67. @property (nonatomic) BOOL keybarShow;
  68. @property (nonatomic) BOOL canloadhistory;
  69. @property (nonatomic) BOOL canloadhistoryMore;
  70. @property (nonatomic) CGFloat offset;
  71. @property (nonatomic,strong) NSString *username;
  72. @property (nonatomic,strong) NSString *useravatar;
  73. @property (nonatomic,strong) UITextView *textV;
  74. @property (nonatomic,strong) chatpopView *popView;
  75. @property (nonatomic,strong) UIView *markView;
  76. @property (nonatomic, strong) ChatBatchView * batchView;
  77. @property (nonatomic, strong) ChatQuoteView * quoteView;
  78. @property (nonatomic, assign) BOOL isQuoteMessage;
  79. @property (strong, nonatomic) NSTimer *timer;
  80. @property (nonatomic, strong) NSDictionary * groupInfo;
  81. @property (nonatomic,strong) NSMutableArray *messageArray;
  82. @property (nonatomic, strong) NSMutableArray * forwordMsgArray;
  83. @property (nonatomic, strong) NSMutableArray * atSomeoneArray;
  84. @property (nonatomic, assign) BOOL isBatchMode;
  85. @property (nonatomic, assign) BOOL showLoading;
  86. @end
  87. @implementation ChatController
  88. - (UIStatusBarStyle)preferredStatusBarStyle {
  89. return UIStatusBarStyleLightContent;
  90. }
  91. -(void)viewDidLoad{
  92. [super viewDidLoad];
  93. [self.navigationController setNavigationBarHidden:YES animated:NO];
  94. [self._tableView registerClass:chatCellView.class forCellReuseIdentifier:@"chatCellView"];
  95. self._tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  96. self._tableView.backgroundColor = [UIColor clearColor];
  97. self._tableView.delegate=self;
  98. self._tableView.dataSource = self;
  99. _isfriend=true;
  100. CGFloat safeBottom = [UIDevice safeDistanceBottom];
  101. UIView *temp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 60+safeBottom)];
  102. temp.backgroundColor = UIColor.blackColor;
  103. [_bottonView insertSubview:temp atIndex:0];
  104. //输入框
  105. _inputView = [[MentionTextView alloc] initWithFrame:CGRectMake(54, 10, self.view.frame.size.width - 180, 40)];
  106. _inputView.backgroundColor = globalColor(GCTypeDark2);
  107. _inputView.layer.cornerRadius = 4.0;
  108. _inputView.textColor = [UIColor blackColor];
  109. _inputView.font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
  110. [_bottonView addSubview:_inputView];
  111. _inputView.delegate = self; // 设置代理
  112. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  113. [_inputView setup];
  114. //删除@用户名
  115. weakSelf(self);
  116. _inputView.mentionDeleteHandler = ^(NSString * _Nonnull deletedMention, NSUInteger index) {
  117. // NSLog(@"第%ld---%@",index,deletedMention);
  118. // NSLog(@"weakself.atSomeoneArray:%@",weakself.atSomeoneArray);
  119. if ([deletedMention isEqualToString:@"@所有人"]) {
  120. return;
  121. }
  122. [weakself removeAtList:index];
  123. };
  124. [_inputView mas_makeConstraints:^(MASConstraintMaker *make) {
  125. // make.height.mas_equalTo(40);
  126. make.left.equalTo(self.yuyinctr.mas_right).mas_offset(10);
  127. make.right.equalTo(self.gengduoBt.mas_left).mas_offset(-10);
  128. make.bottom.mas_offset(-10);
  129. make.top.mas_offset(10);
  130. }];
  131. //录音按钮
  132. _AVRecordBt = [[UIButton alloc] initWithFrame:CGRectMake(54, 10, self.view.frame.size.width - 180, 40)];
  133. [_bottonView addSubview:_AVRecordBt];
  134. _AVRecordBt.alpha = 0;
  135. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeDark2).CGColor;
  136. _AVRecordBt.layer.cornerRadius = 4.0;
  137. [_AVRecordBt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  138. [_AVRecordBt setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
  139. [_AVRecordBt setTitle:@" 按住 说话" forState:UIControlStateNormal];
  140. [_AVRecordBt addTarget:self action:@selector(longTarget) forControlEvents:UIControlEventTouchDown];
  141. [_AVRecordBt addTarget:self action:@selector(UpInside) forControlEvents:UIControlEventTouchUpInside];
  142. [self.bottonView addSubview:self.quoteView];
  143. [self.quoteView mas_makeConstraints:^(MASConstraintMaker *make) {
  144. make.left.mas_equalTo(_inputView.mas_left);
  145. make.size.mas_equalTo(CGSizeMake(SCREEN_WIDTH-180, 30));
  146. make.top.mas_equalTo(self.inputView.mas_bottom).offset(8);
  147. }];
  148. // 注册键盘显示通知
  149. [[NSNotificationCenter defaultCenter] addObserver:self
  150. selector:@selector(keyboardWillShow:)
  151. name:UIKeyboardWillShowNotification object:nil];
  152. // 注册键盘隐藏通知
  153. [[NSNotificationCenter defaultCenter] addObserver:self
  154. selector:@selector(keyboardWillHide:)
  155. name:UIKeyboardWillHideNotification object:nil];
  156. //nkonNewMessageNote
  157. [[NSNotificationCenter defaultCenter] addObserver:self
  158. selector:@selector(othersChatMessageAlert:)
  159. name:nkonNewMessageNote
  160. object:nil];
  161. [self inidatastate];
  162. _textV=[[UITextView alloc] init];
  163. _markView=[[UIView alloc] init];
  164. [self.view addSubview:_markView];
  165. NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"chatpopView" owner:self options:nil];
  166. _popView = [nibs objectAtIndex:0];
  167. [self.view addSubview:_popView];
  168. _popView.delegate= self;
  169. [self initpopbottonView];
  170. [self setupPreloader];
  171. NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  172. NSLog(@"viewDidLoad userinfo:%@",userinfo);
  173. self.userId = userinfo[@"id"];
  174. self.username = userinfo[@"name"];
  175. self.useravatar = userinfo[@"avatar"];
  176. ChatsStore.shareInstance.delegate = self;
  177. ChatsStore.shareInstance.chatId = self.chatId;
  178. ChatsStore.shareInstance.userid =self.userId;
  179. ChatListStore.shareInstance.chatId = self.chatId;
  180. [ChatsStore.shareInstance getchatReadTime:self.chatId];
  181. [OSSManager sharedManager].delegate = self;
  182. _showLoading = YES;
  183. NSString *type=@"";
  184. if(self.type==0){
  185. type=@"0";
  186. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  187. }
  188. else if(self.type==1){
  189. type=@"1";
  190. // [ChatsStore.shareInstance reloadQunData:@"1871105598206210050" type:self.type];
  191. [ChatsStore.shareInstance getGroupUserList:self.chatId];
  192. [self getGroupInfo];
  193. }
  194. _canloadhistory=true;
  195. NSDictionary *chatMsg=@{
  196. @"chatId":self.chatId,
  197. @"name":self.titlename?:@"",
  198. @"avatar":self.avatar?:@"",
  199. @"type":type
  200. };
  201. // NSLog(@"self.chatId:%@",self.chatId);
  202. [ChatListStore.shareInstance chatDidOpen:chatMsg];
  203. [GWebSocket.shareInstance chekWebSocket];
  204. }
  205. -(void)reloadAllData{
  206. [self.messageArray removeAllObjects];
  207. self.msgList = @[];
  208. [__tableView reloadData];
  209. _titlelb.text = self.titlename;
  210. ChatsStore.shareInstance.delegate = self;
  211. [OSSManager sharedManager].delegate = self;
  212. ChatsStore.shareInstance.chatId = self.chatId;
  213. ChatsStore.shareInstance.userid =self.userId;
  214. ChatListStore.shareInstance.chatId = self.chatId;
  215. [ChatsStore.shareInstance getchatReadTime:self.chatId];
  216. NSString *type=@"";
  217. if(self.type==0){
  218. type=@"0";
  219. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  220. }
  221. else if(self.type==1){
  222. type=@"1";
  223. // [ChatsStore.shareInstance reloadQunData:@"1871105598206210050" type:self.type];
  224. [ChatsStore.shareInstance getGroupUserList:self.chatId];
  225. [self getGroupInfo];
  226. }
  227. _canloadhistory=true;
  228. NSDictionary *chatMsg=@{
  229. @"chatId":self.chatId,
  230. @"name":self.titlename?:@"",
  231. @"avatar":self.avatar?:@"",
  232. @"type":type
  233. };
  234. // NSLog(@"self.chatId:%@",self.chatId);
  235. [ChatListStore.shareInstance chatDidOpen:chatMsg];
  236. [GWebSocket.shareInstance chekWebSocket];
  237. [self movetoBotton];
  238. }
  239. - (void)dealloc {
  240. // NSLog(@"dealloc-----:%@",self);
  241. [self.preloader stopMonitoring];
  242. [[NSNotificationCenter defaultCenter] removeObserver:self];
  243. ChatsStore.shareInstance.delegate = nil;
  244. [OSSManager sharedManager].delegate = nil;
  245. ChatsStore.shareInstance.chatId = nil;
  246. }
  247. -(void)viewDidAppear:(BOOL)animated{
  248. [super viewDidAppear:animated];
  249. _titlelb.text = self.titlename;
  250. [self startTimer];
  251. // NSLog(@"viewDidAppear-----:%@",self);
  252. }
  253. -(void)viewWillDisappear:(BOOL)animated{
  254. [super viewWillDisappear:animated];
  255. [self endTimer];
  256. // NSLog(@"viewWillDisappear-----");
  257. }
  258. - (ChatBatchView *)batchView{
  259. if (!_batchView) {
  260. _batchView = [[ChatBatchView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_X_BTM+64)];
  261. [self.view addSubview:_batchView];
  262. }
  263. return _batchView;
  264. }
  265. - (ChatQuoteView *)quoteView{
  266. if (!_quoteView) {
  267. _quoteView = [[ChatQuoteView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-180, 30)];
  268. _quoteView.hidden = YES;
  269. [_quoteView.closeBtn addTarget:nil action:@selector(closeQuoteView) forControlEvents:UIControlEventTouchUpInside];
  270. // [_quoteView.closeBtn jk_addActionHandler:^(NSInteger tag) {
  271. // [self closeQuoteView];
  272. // }];
  273. }
  274. return _quoteView;
  275. }
  276. -(NSMutableArray *)messageArray{
  277. if (!_messageArray) {
  278. _messageArray = [NSMutableArray array];
  279. }
  280. return _messageArray;
  281. }
  282. -(NSMutableArray *)forwordMsgArray{
  283. if (!_forwordMsgArray) {
  284. _forwordMsgArray = [NSMutableArray array];
  285. }
  286. return _forwordMsgArray;
  287. }
  288. -(NSMutableArray *)atSomeoneArray{
  289. if (!_atSomeoneArray) {
  290. _atSomeoneArray = [NSMutableArray array];
  291. }
  292. return _atSomeoneArray;
  293. }
  294. -(void)inidatastate{
  295. [FriendNetApi isfriend:self.chatId succ:^(int code, NSDictionary * res) {
  296. NSLog(@"isfriend:%@",[res[@"data"] class]);
  297. BOOL state = res[@"data"];
  298. if(state){
  299. NSLog(@"isfriend1:");
  300. self.isfriend = true;
  301. }
  302. else{
  303. NSLog(@"isfriend2:");
  304. self.isfriend=false;
  305. }
  306. } fail:^(NSError * _Nonnull error) {
  307. }];
  308. }
  309. -(void)initpopbottonView{
  310. [self hidBottonView];
  311. // UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
  312. // // 将手势添加到主视图上
  313. // [self.view addGestureRecognizer:tap];
  314. UITapGestureRecognizer *tapbotton = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissBotton)];
  315. // 将手势添加到主视图上
  316. [_markView addGestureRecognizer:tapbotton];
  317. _keybarShow=false;
  318. }
  319. - (IBAction)fanhui:(id)sender {
  320. NSLog(@"fanhui-------");
  321. [self dismissViewControllerAnimated:YES completion:nil];
  322. }
  323. - (IBAction)rightBt:(id)sender {
  324. if (self.type==0) {
  325. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  326. FriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"FriendController"];
  327. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  328. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  329. friendctr.friendMsg = nil;
  330. friendctr.friendId = self.chatId;
  331. [self presentViewController :uiNavC animated:YES completion:nil];
  332. }
  333. else{
  334. UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  335. GroupController *friendctr = [board instantiateViewControllerWithIdentifier:@"GroupController"];
  336. UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  337. uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  338. friendctr.groupMsg = nil;
  339. friendctr.groupId = self.chatId;
  340. [self presentViewController :uiNavC animated:YES completion:nil];
  341. }
  342. }
  343. - (IBAction)yuyinBt:(id)sender {
  344. if(_AVRecordBt.alpha==1){
  345. _AVRecordBt.alpha = 0;
  346. _inputView.alpha = 1;
  347. [_yuyinctr setImage:[UIImage imageNamed:@"yuyin"] forState:UIControlStateNormal];
  348. [self dismissKeyboard];
  349. }
  350. else{
  351. _AVRecordBt.alpha = 1;
  352. _inputView.alpha = 0;
  353. [_yuyinctr setImage:[UIImage imageNamed:@"jianpan"] forState:UIControlStateNormal];
  354. }
  355. }
  356. - (IBAction)biaoqingBt:(id)sender {
  357. }
  358. - (IBAction)gengduo:(id)sender {
  359. [self showBottonView];
  360. }
  361. - (IBAction)fasongBt:(id)sender {
  362. NSLog(@"fasongBt:1");
  363. if(_isfriend){
  364. NSLog(@"fasongBt:2");
  365. [self sendtextData];
  366. }
  367. else{//提示不是好友
  368. NSLog(@"fasongBt:3");
  369. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"不是好友关系" preferredStyle:UIAlertControllerStyleAlert];
  370. [self presentViewController:alert animated:NO completion:nil];
  371. NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:2.5 target:self selector:@selector(dismissAlert:) userInfo:alert repeats:NO];
  372. }
  373. //[app showAlert:@"警告" msg:@"不是好友关系" timelate:2];
  374. }
  375. - (void)dismissAlert:(NSTimer *)timer {
  376. UIAlertController *alert = [timer userInfo];
  377. [alert dismissViewControllerAnimated:YES completion:nil];
  378. alert = nil;
  379. }
  380. #pragma mark 群信息
  381. - (void)getGroupInfo{
  382. [GroupNetApi getGroupInfo:self.chatId succ:^(int code, NSDictionary * _Nullable result) {
  383. // NSLog(@"GroupInfo:----%@",result);
  384. self.groupInfo = result[@"data"];
  385. self.titlename = self.groupInfo[@"name"];
  386. self.titlelb.text = self.groupInfo[@"name"];
  387. } fail:^(NSError * _Nonnull error) {
  388. NSLog(@"error:%@",error);
  389. }];
  390. }
  391. #pragma mark ChatsStoreDelegate
  392. -(void)getlocalData{
  393. [ChatsStore.shareInstance reloadData:self.chatId type:self.type];
  394. }
  395. -(void)ChatsChange:(NSArray *)msgList type:(NSInteger)typpe{
  396. // NSLog(@"msgList:%@",msgList);
  397. if([msgList count]==0){
  398. return;
  399. }
  400. if(self.msgList.count>0){
  401. NSArray *array = msgList.copy;
  402. NSMutableArray *marray = [NSMutableArray new];
  403. // [marray addObjectsFromArray:self.msgList];
  404. [marray addObjectsFromArray:array];
  405. NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:marray];
  406. NSMutableArray *uniqueArray = [orderedSet.array mutableCopy];
  407. self.msgList = [ChatsStore.shareInstance arraysort:uniqueArray];
  408. }
  409. else{
  410. self.msgList = msgList.copy;
  411. NSMutableArray *array = [NSMutableArray new];
  412. [array addObjectsFromArray:self.msgList];
  413. NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:array];
  414. NSMutableArray *uniqueArray = [orderedSet.array mutableCopy];
  415. self.msgList = [ChatsStore.shareInstance arraysort:uniqueArray];
  416. }
  417. // NSLog(@"self.msgList11:%@",self.msgList);
  418. NSMutableArray * tempArray = [NSMutableArray array];
  419. for (NSDictionary * msg in self.msgList) {
  420. // NSLog(@"msg:%@",msg);
  421. ChatMessageModel *message = [ChatMessageModel modelWithDictionary:msg];
  422. if (message.avatar.length==0 && message.isSender) {
  423. message.avatar = self.useravatar;
  424. }else if (message.avatar.length==0 && !message.isSender) {
  425. message.avatar = self.avatar;
  426. }
  427. if ([message.chatId isEqualToString:self.chatId]) {
  428. [tempArray addObject:message];
  429. }
  430. }
  431. // NSLog(@"----222---:coun-------:%lu",(unsigned long)tempArray.count);
  432. NSMutableArray * indexPathArray = [NSMutableArray array];
  433. BOOL isHistoryRecord = NO;
  434. if (self.messageArray.count == 0) {
  435. [self.messageArray removeAllObjects];
  436. [self.messageArray addObjectsFromArray:tempArray];
  437. // NSLog(@"----222---:count ==%lu",(unsigned long)self.messageArray.count);
  438. //禁用隐式动画 加载历史消息
  439. [CATransaction begin];
  440. [CATransaction setDisableActions:YES];
  441. [self._tableView reloadData];
  442. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  443. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  444. [CATransaction commit];
  445. [self.preloader startMonitoring];
  446. [self faSongYidu];
  447. _canloadhistory = true;
  448. return;
  449. }else{
  450. for (ChatMessageModel *message in tempArray) {
  451. BOOL isContain = NO;
  452. // NSLog(@"----333---:%ld",(long)message.localtime);
  453. for (ChatMessageModel * localMessage in self.messageArray) {
  454. if (localMessage.localtime==message.localtime) {
  455. isContain = YES;
  456. if (![message.url isEqualToString:localMessage.url] || ![message.readStatus isEqualToString:localMessage.readStatus]||localMessage.messageType!=message.messageType) {
  457. [localMessage exchangeModelWithModel:message];
  458. // NSLog(@"----11---:%@",message.content);
  459. dispatch_async(dispatch_get_main_queue(), ^{
  460. [CATransaction begin];
  461. [CATransaction setDisableActions:YES];
  462. NSIndexPath *reloadIndexPath = [NSIndexPath indexPathForRow:[self.messageArray indexOfObject:localMessage] inSection:0];
  463. [self._tableView beginUpdates];
  464. [self._tableView reloadRowsAtIndexPaths:@[reloadIndexPath] withRowAnimation:UITableViewRowAnimationNone];
  465. [self._tableView endUpdates];
  466. [CATransaction commit];
  467. });
  468. }else{
  469. [localMessage exchangeModelWithModel:message];
  470. // NSLog(@"----222---:%@",message.content);
  471. }
  472. }
  473. else{
  474. // NSLog(@"1122211------");
  475. }
  476. }
  477. if (!isContain) {
  478. // NSLog(@"!isContain");
  479. ChatMessageModel *lastObj = self.messageArray.lastObject;
  480. if (lastObj.timestamp > message.timestamp) {
  481. //插入历史消息
  482. for (ChatMessageModel * localMessage in self.messageArray) {
  483. if(localMessage.timestamp>message.timestamp){
  484. NSInteger index = [self.messageArray indexOfObject:localMessage];
  485. // NSLog(@"插入历史消息1------:%@",message.content);
  486. // NSLog(@"index:%ld",(long)index);
  487. [self.messageArray insertObject:message atIndex:index];
  488. NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
  489. [indexPathArray addObject:newIndexPath];
  490. break;
  491. }
  492. }
  493. }else{
  494. // NSLog(@"插入历史消息2------:%@",message.content);
  495. isHistoryRecord = NO;
  496. [self.messageArray addObject:message];
  497. NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:self.messageArray.count-1 inSection:0];
  498. [indexPathArray addObject:newIndexPath];
  499. }
  500. }
  501. else{
  502. // NSLog(@"插入历史消息6------:%@",message.content);
  503. }
  504. }
  505. }
  506. if (indexPathArray.count == 0) {
  507. if(msgList.count>0){
  508. _canloadhistory = true;
  509. }
  510. else{
  511. _canloadhistory = false;
  512. }
  513. return;
  514. }
  515. // NSLog(@"----222444---:count ==%lu",(unsigned long)self.messageArray.count);
  516. if (isHistoryRecord) {
  517. // 执行插入操作(禁用动画)
  518. for (NSIndexPath * index in indexPathArray) {
  519. if (index.row>=self.messageArray.count) {
  520. return;
  521. }
  522. }
  523. [CATransaction begin];
  524. [CATransaction setDisableActions:YES];
  525. [self._tableView beginUpdates];
  526. [self._tableView insertRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationNone];
  527. [self._tableView endUpdates];
  528. [CATransaction commit];
  529. [self.preloader resetScrollState];
  530. if(msgList.count>0){
  531. _canloadhistory = true;
  532. }
  533. else{
  534. _canloadhistory = false;
  535. }
  536. }else{
  537. [CATransaction begin];
  538. [CATransaction setDisableActions:YES];
  539. [self._tableView beginUpdates];
  540. [self._tableView insertRowsAtIndexPaths:indexPathArray
  541. withRowAnimation:UITableViewRowAnimationNone];
  542. [self._tableView endUpdates];
  543. [CATransaction commit];
  544. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  545. //插入新消息时,判断是否在底部附近,在底部附近则滚动至底部,不在底部则不打断用户浏览
  546. CGFloat visibleHeight = self._tableView.bounds.size.height - self._tableView.contentInset.top - self._tableView.contentInset.bottom;
  547. CGFloat yOffset = self._tableView.contentOffset.y;
  548. CGFloat threshold = MAX(20, visibleHeight * 0.8); // 距离底部20点或20%可见高度
  549. // NSLog(@"threshold:%f,%f",threshold,self._tableView.contentSize.height - yOffset - visibleHeight);
  550. BOOL shouldScrollToBottom = (self._tableView.contentSize.height - yOffset - visibleHeight) <= threshold;
  551. if (shouldScrollToBottom) {
  552. [CATransaction begin];
  553. [CATransaction setDisableActions:YES];
  554. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  555. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  556. [CATransaction commit];
  557. }
  558. });
  559. [self faSongYidu];
  560. if(msgList.count>0){
  561. _canloadhistory = true;
  562. }
  563. else{
  564. _canloadhistory = false;
  565. }
  566. }
  567. if(self.messageArray.count>20){
  568. _showLoading = false;
  569. }
  570. else{
  571. _showLoading = true;
  572. }
  573. }
  574. -(void)movetoBotton{
  575. // NSLog(@"movetoBotton------movetoBotton");
  576. if (self.messageArray.count>0) {
  577. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  578. NSIndexPath *lastRowIndexPath = [NSIndexPath indexPathForRow:([self._tableView numberOfRowsInSection:0] - 1) inSection:0];
  579. //NSLog(@"lastRowIndexPath:%ld",(long)lastRowIndexPath.row);
  580. [self._tableView scrollToRowAtIndexPath:lastRowIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
  581. });
  582. }
  583. }
  584. #pragma mark chatpopViewDelegate
  585. -(void)actionNote:(NSString *)note{
  586. [self hidBottonView];
  587. if([note isEqualToString:@"1"]){//发送图片
  588. [self showImagePicker:1];
  589. }
  590. if([note isEqualToString:@"2"]){//发送视频
  591. [self showImagePicker:2];
  592. }
  593. if([note isEqualToString:@"3"]){//发送文件
  594. [self showfilePicker];
  595. }
  596. if([note isEqualToString:@"4"]){//语音
  597. [self showWebRtcVidio:4];
  598. }
  599. if([note isEqualToString:@"5"]){//视频
  600. [self showWebRtcVidio:5];
  601. }
  602. if([note isEqualToString:@"6"]){//拍摄
  603. [self takePhoto];
  604. }
  605. }
  606. #pragma mark preload
  607. -(void)setupPreloader{
  608. //预加载管理器
  609. NSLog(@"setupPreloader");
  610. self.preloader = [[HistoryPreloader alloc] init];
  611. self.preloader.tableView = self._tableView;
  612. self.preloader.threshold = 700;
  613. weakSelf(self);
  614. self.preloader.loadBlock = ^{
  615. if (!weakself.canloadhistory) {
  616. return;
  617. }
  618. [weakself loadhistoryData];
  619. };
  620. self.preloader.toofast = ^{
  621. if (weakself.showLoading) {
  622. }else{
  623. weakself.showLoading = YES;
  624. // [MBProgressHUD showLoadingWithText:@"數據解密中。。。。" inView:weakself.view hideAfterDelay:2];
  625. }
  626. };
  627. }
  628. -(void)loadhistoryData{
  629. if(self.messageArray.count>0){
  630. NSLog(@"loadhistoryData-------");
  631. _canloadhistory = false;
  632. if(self.type==0){
  633. ChatMessageModel *eldata = self.messageArray[0];
  634. NSInteger time =eldata.timestamp;
  635. [ChatsStore.shareInstance loadNextData:self.chatId timestp:time];
  636. }
  637. else if(self.type==1){
  638. ChatMessageModel *eldata = self.messageArray[0];
  639. NSInteger time =eldata.timestamp;
  640. [ChatsStore.shareInstance loadQunNextData:self.chatId timestp:time];
  641. }
  642. }
  643. }
  644. #pragma mark UITableViewDelegate,UITableViewDataSource
  645. -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
  646. return 1;
  647. }
  648. -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
  649. return self.messageArray.count;
  650. }
  651. -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
  652. if(self.messageArray.count<indexPath.row){
  653. return nil;
  654. }
  655. static NSString *cellID = @"chatCellView";
  656. chatCellView *cell =[tableView dequeueReusableCellWithIdentifier:cellID];
  657. if(cell==nil){
  658. cell=[[chatCellView alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
  659. }
  660. cell.parentViewController = self;
  661. cell.isHistory = false;
  662. ChatMessageModel *message = self.messageArray[indexPath.row];
  663. // NSLog(@"---:%ld,%@",(long)message.localtime,message.content);
  664. weakSelf(self);
  665. cell.bubbleCellLongPressMenuBlock = ^(NSInteger index) {
  666. switch (index) {
  667. case 0:
  668. NSLog(@"-------复制------");
  669. [weakself copyMessageContent:message.content];
  670. break;
  671. case 1:
  672. NSLog(@"------删除------");
  673. [weakself deleteMyMsg:message.formerMessage];
  674. break;
  675. case 2:
  676. NSLog(@"-----转发-------");
  677. [weakself forwardMsg:@[message.formerMessage] isMultiple:NO];
  678. break;
  679. case 3:
  680. NSLog(@"-----收藏-------");
  681. [weakself addFavorites:message.formerMessage];
  682. break;
  683. case 4:
  684. NSLog(@"------撤回------");
  685. [weakself messageCallback:message.formerMessage];
  686. break;
  687. case 5:
  688. NSLog(@"------多选------");
  689. [weakself batchProcess];
  690. break;
  691. case 6:
  692. NSLog(@"------引用------");
  693. [weakself quoteMessage:message];
  694. break;
  695. case 7:
  696. NSLog(@"------保存------");
  697. [weakself saveFile:message];
  698. break;
  699. // case 8:
  700. // NSLog(@"------文件视频图片重新上传------");
  701. // [weakself resendFile:message];
  702. // break;
  703. case 99:
  704. // NSLog(@"------长按开始------");
  705. [weakself dismissKeyboard];
  706. break;
  707. default:
  708. break;
  709. }
  710. };
  711. cell.batchSelectedStateBlock = ^(BOOL isSelected) {
  712. if (isSelected) {
  713. NSMutableDictionary *dic =message.formerMessage.mutableCopy;
  714. NSString *coontent = dic[@"content"]?:@"";
  715. coontent =[CryptoAES.shareInstance encryptStringL:coontent];
  716. [dic setObject:coontent forKey:@"content"];
  717. [weakself.forwordMsgArray addObject:dic];
  718. }else{
  719. [weakself.forwordMsgArray removeObject:message.formerMessage];
  720. }
  721. NSLog(@"weakself.forwordMsgArray:%@",weakself.forwordMsgArray);
  722. };
  723. cell.avatarTapBlock = ^(ChatMessageModel * _Nonnull message) {
  724. // if (message.isSender) {
  725. // return;
  726. // }
  727. // //前往用户信息页
  728. // UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
  729. // FriendController *friendctr = [board instantiateViewControllerWithIdentifier:@"FriendController"];
  730. // friendctr.friendMsg = nil;
  731. // friendctr.friendId = message.fromId;
  732. //
  733. // UINavigationController *uiNavC = [[UINavigationController alloc] initWithRootViewController:friendctr];
  734. // uiNavC.modalPresentationStyle = UIModalPresentationFullScreen;
  735. //
  736. // [weakself presentViewController :uiNavC animated:YES completion:nil];
  737. };
  738. [cell setResendMessageBlock:^(ChatMessageModel *message) {
  739. if (message.isUploadFile) {
  740. [weakself resendFile:message];
  741. } else {
  742. [weakself resendMsg:message.formerMessage];
  743. }
  744. }];
  745. return cell;
  746. }
  747. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  748. ChatMessageModel *message = self.messageArray[indexPath.row];
  749. // NSLog(@"heightForRowAtIndexPath-----");
  750. return [chatCellView cellHeightForMessage:message];
  751. }
  752. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
  753. chatCellView * currentCell = (chatCellView *)cell;
  754. ChatMessageModel *message = self.messageArray[indexPath.row];
  755. currentCell.messageModel = message;
  756. // NSLog(@"willDisplayCell-----");
  757. currentCell.batchState = self.isBatchMode;
  758. }
  759. -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
  760. if(_keybarShow){
  761. [self dismissKeyboard];
  762. return;
  763. }
  764. }
  765. -(void)scrollViewDidScroll:(UIScrollView *)scrollView{
  766. // 计算距离顶部的距离
  767. // CGFloat offsetY = scrollView.contentOffset.y;
  768. // CGFloat contentHeight = scrollView.contentSize.height;
  769. // CGFloat frameHeight = scrollView.frame.size.height;
  770. //// NSLog(@"scrollViewDidScroll:offsetY:%f,contentHeight:%f,frameHeight:%f",offsetY,contentHeight,frameHeight);
  771. // // 预加载阈值(距离顶部300pt时触发)
  772. // CGFloat threshold = 300.0;
  773. //// NSLog(@"scrollViewDidScroll:%f",offsetY);
  774. // if (offsetY > threshold&&!_canloadhistory) {
  775. // _canloadhistory=true;
  776. // _offset =offsetY;
  777. // return;
  778. // }
  779. // if(_offset-offsetY>400){
  780. // _canloadhistoryMore=false;
  781. // }
  782. //
  783. // if(_canloadhistory&&offsetY < threshold){
  784. //// NSLog(@"-----1------1");
  785. // if(!_canloadhistoryMore){
  786. //// NSLog(@"-----1------2");
  787. // _ishistory=true;
  788. // [self loadhistoryData];
  789. // }
  790. // }
  791. }
  792. -(void)saveFile:(ChatMessageModel *)msgMdl{
  793. NSString *localPath =msgMdl.localurl;
  794. if (localPath && [[NSFileManager defaultManager] fileExistsAtPath:localPath]) {
  795. NSLog(@"本地路径");
  796. NSString *fileExtension = [[msgMdl.localurl pathExtension] lowercaseString];
  797. if([self isVideoFile:fileExtension]){
  798. NSURL *fileURL = [NSURL fileURLWithPath:localPath];
  799. [self saveVideoToPhotoLibrary:fileURL];
  800. }
  801. else{
  802. [self saveFileToLibrary:localPath];
  803. }
  804. }
  805. else{
  806. [MBProgressHUD showWithText:@"文件尚未加载完成,请稍后重试"];
  807. }
  808. }
  809. - (BOOL)isVideoFile:(NSString *)fileExtension {
  810. NSArray *videoExtensions = @[@"mp4", @"mov", @"m4v", @"avi", @"mkv", @"flv", @"wmv"];
  811. return [videoExtensions containsObject:fileExtension];
  812. }
  813. - (void)saveVideoToPhotoLibrary:(NSURL *)videoURL {
  814. // 检查 PHPhotoLibrary 的授权状态
  815. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  816. if (status == PHAuthorizationStatusAuthorized) {
  817. // 授权成功,保存视频
  818. [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
  819. // 创建资产更改请求
  820. PHAssetChangeRequest *assetChangeRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:videoURL];
  821. // 可以设置其他属性,如位置信息等
  822. // [assetChangeRequest setLocation:location];
  823. } completionHandler:^(BOOL success, NSError *error) {
  824. if (success) {
  825. NSLog(@"视频保存成功");
  826. dispatch_async(dispatch_get_main_queue(), ^{
  827. [self showNot:@"保存到手机成功"];
  828. });
  829. } else {
  830. NSLog(@"视频保存失败: %@", error.localizedDescription);
  831. }
  832. }];
  833. } else {
  834. // 授权失败或未授权,处理用户未授权的情况
  835. NSLog(@"请在设置中授权访问相册");
  836. }
  837. }];
  838. }
  839. -(void)showNot:(NSString *)str{
  840. [MBProgressHUD showWithText:str];
  841. }
  842. -(void)saveFileToLibrary:(NSString *)fileUrl{
  843. NSURL *fileURL = [NSURL fileURLWithPath:fileUrl];
  844. UIDocumentInteractionController *documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
  845. [documentController presentOptionsMenuFromRect:CGRectZero inView:self.view animated:YES];
  846. }
  847. #pragma mark UITextViewDelegate
  848. - (void)textViewDidChange:(UITextView *)textView {
  849. CGFloat maxHeight = 160;
  850. CGFloat maxWidth = self.view.frame.size.width - 190;
  851. CGSize newSize = [textView sizeThatFits:CGSizeMake(maxWidth, MAXFLOAT)];
  852. if(newSize.height>maxHeight){
  853. _inputView.scrollEnabled = YES; // 允许滚动,出现滚动条
  854. }
  855. else{
  856. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  857. [self movetoBotton];
  858. }
  859. CGFloat height = MAX(40, MIN(maxHeight, newSize.height));
  860. self.bottomViewHeight.constant = height+20;
  861. }
  862. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
  863. // 计算新文本的长度
  864. NSInteger newLength = textView.text.length - range.length + text.length;
  865. NSLog(@"shouldChangeTextInRange---");
  866. // 若新文本长度超出最大长度,则不允许输入
  867. if (newLength > 1000) {
  868. [MBProgressHUD showWithText:@"超出最大文本长度,请重新输入"];
  869. if (textView.text.length == 0) {
  870. return NO;
  871. }
  872. // 截取最大长度的文本
  873. NSString *substring = [textView.text substringToIndex:1000];
  874. textView.text = substring;
  875. return NO;
  876. }
  877. if ([text isEqualToString:@"@"] && self.type == 1) {
  878. NSLog(@"用户输入了@符号");
  879. // 可以在这里添加你需要执行的代码
  880. [textView resignFirstResponder];
  881. [self showAtMemberView];
  882. }
  883. if ([text isEqualToString:@""] && self.type == 1) { // 删除操作
  884. // 处理连续删除特殊字符的情况
  885. if (range.length == 1) {
  886. NSRange deleteRange = range;
  887. NSString *deletedChar = [textView.text substringWithRange:deleteRange];
  888. // 如果删除的是连字符,尝试删除整个mention
  889. if ([deletedChar isEqualToString:@"-"]) {
  890. if ([self.inputView deleteMentionAtCursorPosition]) {
  891. return NO;
  892. }
  893. }
  894. }
  895. NSLog(@"1111111");
  896. // 正常删除处理
  897. if ([self.inputView deleteMentionAtCursorPosition]) {
  898. NSLog(@"deleteMentionAtCursorPosition");
  899. return NO;
  900. }
  901. }
  902. return YES;
  903. }
  904. - (void)keyboardWillShow:(NSNotification *)notification {
  905. // 获取键盘的动画持续时间和动画曲线
  906. NSDictionary *userInfo = [notification userInfo];
  907. double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  908. // UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  909. //
  910. // 获取键盘的高度
  911. CGRect keyboardEndFrame = [[userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
  912. _keyboardHeight = keyboardEndFrame.size.height;
  913. NSLog(@"_keyboardHeight:%f",_keyboardHeight);
  914. // 根据需要调整视图大小或位置(例如,移动某个视图)
  915. // 示例:将一个视图向下移动以适应键盘高度
  916. CGFloat safeBottom = [UIDevice safeDistanceBottom];
  917. CGFloat offsetY = _keyboardHeight - safeBottom;
  918. _gengduoBt.alpha = 1;
  919. _fasngBt.alpha = 1;
  920. _keybarShow=true;
  921. [UIView animateWithDuration:duration
  922. delay:0
  923. options:UIViewAnimationOptionCurveEaseInOut
  924. animations:^{
  925. self.inputViewBottom.constant = offsetY;
  926. [self.view setNeedsLayout];
  927. [self.view layoutIfNeeded];
  928. } completion:^(BOOL finished) {
  929. [self movetoBotton];
  930. }];
  931. }
  932. - (void)keyboardWillHide:(NSNotification *)notification {
  933. // 获取键盘的动画持续时间和动画曲线
  934. NSDictionary *userInfo = [notification userInfo];
  935. double duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
  936. UIViewAnimationCurve curve = [[userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];
  937. NSLog(@"_keyboardHeight:%f",_keyboardHeight);
  938. [UIView animateWithDuration:duration
  939. delay:0.0
  940. options:(curve << 16)
  941. animations:^{
  942. self.inputViewBottom.constant = 0;
  943. [self.view setNeedsLayout];
  944. [self.view layoutIfNeeded];
  945. } completion:^(BOOL finished) {
  946. [self movetoBotton];
  947. }];
  948. if(_inputView.text.length>0){
  949. _gengduoBt.alpha = 1;
  950. _fasngBt.alpha = 1;
  951. }
  952. else{
  953. _gengduoBt.alpha = 1;
  954. _fasngBt.alpha = 1;
  955. }
  956. _keybarShow=false;
  957. }
  958. -(void)dismissKeyboard{
  959. [self.view endEditing:YES];
  960. }
  961. -(void)fasongwanwenzi{
  962. CGRect newFrame = _inputView.frame;
  963. newFrame.size.height =40;
  964. _inputView.scrollEnabled = NO; // 禁止滚动,使内容自适应高度
  965. _inputView.frame =newFrame;
  966. CGRect viewFrame = _bottonView.frame;
  967. viewFrame.size.height = 62;
  968. if (self.isQuoteMessage) {
  969. self.quoteView.hidden = YES;
  970. CGRect audioBtnFrame = self.yuyinctr.frame;
  971. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y+kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  972. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  973. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y+kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  974. CGRect sendBtnFrame = self.fasngBt.frame;
  975. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y+kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  976. }
  977. if(_keybarShow){
  978. viewFrame.origin.y =self.view.frame.size.height-_keyboardHeight-viewFrame.size.height;
  979. CGRect tframe = self._tableView.frame;
  980. tframe.size.height = viewFrame.origin.y-tframe.origin.y;
  981. self._tableView.frame = tframe;
  982. [self movetoBotton];
  983. }
  984. else{
  985. // 恢复视图原始位置或大小
  986. viewFrame.origin.y = self.view.frame.size.height-viewFrame.size.height-34;
  987. CGRect tframe = self._tableView.frame;
  988. tframe.size.height = viewFrame.origin.y-tframe.origin.y;
  989. self._tableView.frame = tframe;
  990. [self movetoBotton];
  991. }
  992. _bottonView.frame = viewFrame;
  993. }
  994. #pragma mark 发送数据
  995. -(void)sendtextData{
  996. NSLog(@"sendtextData1");
  997. NSString *msg = _inputView.text;
  998. msg = [msg stringByReplacingOccurrencesOfString:@"\r" withString:@""];
  999. msg = [msg stringByReplacingOccurrencesOfString:@"\n" withString:@""];
  1000. msg = [msg stringByReplacingOccurrencesOfString:@"\t" withString:@""];
  1001. msg = [msg stringByReplacingOccurrencesOfString:@" " withString:@""];
  1002. if (msg.length==0) {
  1003. NSLog(@"空内容");
  1004. return;
  1005. }
  1006. [self fasongwanwenzi];
  1007. NSLog(@"sendtextData2");
  1008. NSDictionary * quoteMessage;
  1009. if (self.isQuoteMessage) {
  1010. // NSInteger quoteIndex = [self.messageArray indexOfObject:self.quoteView.model];
  1011. // NSLog(@"quoteIndex:%ld------------",quoteIndex);
  1012. quoteMessage = self.quoteView.model.formerMessage;
  1013. }
  1014. NSString *content= [CryptoAES.shareInstance encryptStringL:_inputView.text];
  1015. // NSLog(@"content:%@",content);
  1016. NSString *strtime = [self getLocalTime];
  1017. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1018. NSDictionary *Lmsgd=@{
  1019. @"messageType":@"0",
  1020. @"chatId":self.chatId,
  1021. @"fromId":self.userId,
  1022. @"fromName":self.username,
  1023. @"fromAvatar":self.useravatar,
  1024. @"content":content,
  1025. @"type":type,
  1026. @"reSend":[NSNumber numberWithBool:false],
  1027. @"extend": @{
  1028. @"atAll":@"false",
  1029. @"atUserIds":@[],
  1030. },
  1031. @"localtime":strtime,
  1032. @"timestamp":strtime,
  1033. @"mine":@"true",
  1034. @"id":strtime,
  1035. };
  1036. NSMutableDictionary * tempMsgDict = [NSMutableDictionary dictionaryWithDictionary:Lmsgd];
  1037. NSMutableDictionary * tempExtandDict = [NSMutableDictionary dictionaryWithDictionary:Lmsgd[@"extend"]];
  1038. if (quoteMessage) {
  1039. [tempExtandDict setObject:quoteMessage forKey:@"quoteMessage"];
  1040. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1041. }
  1042. if (self.atSomeoneArray.count!=0 && self.type == 1) {
  1043. //@单人或者多人参数插入
  1044. NSMutableArray * atUserIdsArray = [NSMutableArray array];
  1045. for (NSDictionary * user in self.atSomeoneArray) {
  1046. [atUserIdsArray addObject:user[@"id"]];
  1047. }
  1048. [tempExtandDict setObject:atUserIdsArray forKey:@"atUserIds"];
  1049. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1050. }
  1051. if ([self.inputView.text containsString:@"@所有人"] && self.type == 1 && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  1052. [tempExtandDict setObject:@"true" forKey:@"atAll"];
  1053. [tempMsgDict setObject:tempExtandDict forKey:@"extend"];
  1054. }
  1055. NSString * tempChatId = self.chatId.mutableCopy;
  1056. [ChatsStore shareInstance].chatId = tempChatId;
  1057. [ChatsStore shareInstance].delegate = self;
  1058. [ChatsStore.shareInstance reciveMsg:tempMsgDict];//预先展示聊天窗信息
  1059. // NSLog(@"sendtextData3");
  1060. NSDictionary *Smsgd=@{
  1061. @"messageType":@"0",
  1062. @"chatId":self.chatId,
  1063. @"fromId":self.userId,
  1064. @"fromName":self.username,
  1065. @"fromAvatar":self.useravatar,
  1066. @"content":content,
  1067. @"type":type,
  1068. @"reSend":[NSNumber numberWithBool:false],
  1069. @"extend": @{
  1070. @"atAll":@"false",
  1071. @"atUserIds":@[],
  1072. },
  1073. @"localtime":strtime,
  1074. @"timestamp":strtime,
  1075. };
  1076. NSMutableDictionary * tempSendMsgDict = [NSMutableDictionary dictionaryWithDictionary:Smsgd];
  1077. NSMutableDictionary * tempSendExtandDict = [NSMutableDictionary dictionaryWithDictionary:Smsgd[@"extend"]];
  1078. if (quoteMessage) {
  1079. [tempSendExtandDict setObject:quoteMessage forKey:@"quoteMessage"];
  1080. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1081. }
  1082. if (self.atSomeoneArray.count!=0 && self.type == 1) {
  1083. //@单人或者多人参数插入
  1084. NSMutableArray * atUserIdsArray = [NSMutableArray array];
  1085. for (NSDictionary * user in self.atSomeoneArray) {
  1086. [atUserIdsArray addObject:user[@"id"]];
  1087. }
  1088. [tempSendExtandDict setObject:atUserIdsArray forKey:@"atUserIds"];
  1089. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1090. }
  1091. if ([self.inputView.text containsString:@"@所有人"] && self.type == 1 && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  1092. [tempSendExtandDict setObject:@"true" forKey:@"atAll"];
  1093. [tempSendMsgDict setObject:tempSendExtandDict forKey:@"extend"];
  1094. }
  1095. NSDictionary *sendInfo = @{
  1096. @"code":@"2",
  1097. @"message":tempSendMsgDict,
  1098. };
  1099. NSError *error;
  1100. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1101. if (!jsonData) {
  1102. NSLog(@"Got an error: %@", error);
  1103. } else {
  1104. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1105. //NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1106. // NSLog(@"----发送文字----");
  1107. [GWebSocket.shareInstance sendMsg:jsonString];
  1108. if (self.isQuoteMessage) {
  1109. self.isQuoteMessage = NO;
  1110. }
  1111. _inputView.text=@"";
  1112. [self textViewDidChange:_inputView];
  1113. }
  1114. if(_keybarShow){
  1115. _gengduoBt.alpha = 1;
  1116. _fasngBt.alpha = 1;
  1117. }
  1118. else{
  1119. _gengduoBt.alpha = 1;
  1120. _fasngBt.alpha = 1;
  1121. }
  1122. }
  1123. -(void)faSongYidu{
  1124. if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
  1125. // 应用已经解锁并且在前台
  1126. NSLog(@"应用已经解锁并且在前台viewWillDisappear-----1111");
  1127. }
  1128. else{
  1129. return;
  1130. }
  1131. NSString *strtime = [self getLocalTime];
  1132. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1133. NSDictionary *dic =@{
  1134. @"chatId":self.chatId,
  1135. @"userId":self.userId,
  1136. @"type":type,
  1137. @"timestamp":strtime,
  1138. };
  1139. NSDictionary *sendInfo = @{
  1140. @"code":SendCode_READ,
  1141. @"message":dic,
  1142. };
  1143. NSError *error;
  1144. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1145. if (!jsonData) {
  1146. NSLog(@"Got an error: %@", error);
  1147. } else {
  1148. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1149. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1150. // NSLog(@"1--------发送已读时间--------2");
  1151. [GWebSocket.shareInstance sendMsg:jsonString];
  1152. }
  1153. }
  1154. #pragma mark 弹框
  1155. -(void)showBottonView{
  1156. [self dismissKeyboard];
  1157. _markView.frame = self.view.frame;
  1158. CGRect popfram = CGRectMake(0,self.view.frame.size.height-250, self.view.frame.size.width, 250);
  1159. _popView.frame = popfram;
  1160. }
  1161. -(void)hidBottonView{
  1162. CGRect popfram = CGRectMake(0,self.view.frame.size.height, self.view.frame.size.width, 250);
  1163. _popView.frame = popfram;
  1164. _markView.frame=popfram;
  1165. _markView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.5];
  1166. [self movetoBotton];
  1167. }
  1168. -(void)dismissBotton{
  1169. [self hidBottonView];
  1170. }
  1171. #pragma mark 定时服务
  1172. -(void)startTimer{
  1173. if(self.timer==nil){
  1174. self.timer = [NSTimer scheduledTimerWithTimeInterval:10.1 target:self selector:@selector(TimerAction) userInfo:nil repeats:YES];
  1175. [self.timer setFireDate:[NSDate distantPast]];
  1176. [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSRunLoopCommonModes];
  1177. }
  1178. }
  1179. -(void)endTimer{
  1180. [self.timer invalidate];
  1181. self.timer = nil;
  1182. }
  1183. -(void)TimerAction{
  1184. //处理重发事件
  1185. // NSLog(@"self.msgList:%@",self.msgList);
  1186. for(NSDictionary *dis in self.msgList){
  1187. NSString *mine = dis[@"mine"];
  1188. if(mine.boolValue){
  1189. if([dis[@"id"] isEqualToString:dis[@"localtime"]]){
  1190. [self resendMsg:dis.copy];
  1191. }
  1192. }
  1193. }
  1194. }
  1195. -(BOOL)canResend:(NSDictionary *)msg{
  1196. NSLog(@"canResend:%@",msg);
  1197. NSString *localtime = msg[@"localtime"];
  1198. NSString *messageType = msg[@"messageType"];
  1199. if([messageType isEqualToString:MessageType_text]){
  1200. for (NSDictionary *item in self.msgList) {
  1201. NSString *itlocaltime =item[@"localtime"];
  1202. if([localtime isEqualToString:itlocaltime]){
  1203. NSLog(@"canResend2:%@",item);
  1204. if(![item[@"id"] isEqualToString:item[@"localtime"]]){
  1205. return false;
  1206. }
  1207. NSDate *now = [NSDate date];
  1208. NSTimeInterval trt = [now timeIntervalSince1970];
  1209. NSNumber *tt =msg[@"localtime"];
  1210. if((trt-tt.integerValue/1000)>40){
  1211. //发送失败
  1212. NSLog(@"发送失败-------");
  1213. return false;
  1214. }
  1215. }
  1216. }
  1217. }
  1218. else{
  1219. [self fileUploadState:msg];
  1220. return false;
  1221. }
  1222. return YES;
  1223. }
  1224. -(void)fileUploadState:(NSDictionary *)msg{
  1225. NSString *localtime = msg[@"localtime"];
  1226. NSString *messageType = msg[@"messageType"];
  1227. if([messageType isEqualToString:MessageType_file]||[messageType isEqualToString:MessageType_image]||[messageType isEqualToString:MessageType_video]) {
  1228. if([OSSManager.sharedManager isuploadTanck:localtime]){
  1229. return;
  1230. }
  1231. for (NSDictionary *item in self.msgList) {
  1232. NSString *itlocaltime =item[@"localtime"];
  1233. if([localtime isEqualToString:itlocaltime]){
  1234. NSLog(@"canResend2:%@",item);
  1235. if(![item[@"id"] isEqualToString:item[@"localtime"]]){
  1236. return;
  1237. }
  1238. NSDictionary *extend =item[@"extend"];
  1239. NSString *url =extend[@"url"];
  1240. if([url isEqualToString:@""]){
  1241. NSString *savedPath =extend[@"localurl"];
  1242. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1243. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1244. model.fileURL = fileUrl;
  1245. model.filePath = savedPath;
  1246. [self OSSuploadFile:model thrid:localtime];
  1247. NSLog(@"重发文件");
  1248. [self FileReUpload:localtime];
  1249. }
  1250. }
  1251. }
  1252. }
  1253. }
  1254. -(void)FileReUpload:(NSString *)localtime{
  1255. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1256. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1257. if(array){
  1258. if(array.count>0){
  1259. NSDictionary *msg =array[0];
  1260. NSString *msgtype = msg[@"messageType"];
  1261. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  1262. return;
  1263. }
  1264. NSDictionary *extend=msg[@"extend"];
  1265. NSMutableDictionary *mextend = [extend mutableCopy];
  1266. [mextend setObject:[NSNumber numberWithInt:0] forKey:@"fileError"];
  1267. NSMutableDictionary *mmsg = [msg mutableCopy];
  1268. [mmsg setObject:mextend forKey:@"extend"];
  1269. [ChatsStore.shareInstance reciveMsg:mmsg];
  1270. }
  1271. }
  1272. } fail:^(NSString * _Nullable error) {
  1273. ;
  1274. }];
  1275. }
  1276. //重发消息
  1277. -(void)resendMsg:(NSDictionary *)msg{
  1278. if(![self canResend:msg]){
  1279. return;
  1280. }
  1281. NSMutableDictionary *dic = [msg mutableCopy];
  1282. NSString *resend =dic[@"reSend"];
  1283. NSLog(@"resend:%@",[resend class]);
  1284. if (resend.boolValue) {
  1285. return;
  1286. }
  1287. else{
  1288. NSString * str = msg[@"messageType"];
  1289. if (![str isEqualToString:@"0"]) {
  1290. return;
  1291. }
  1292. [dic setObject:[NSNumber numberWithBool:YES] forKey:@"reSend"];
  1293. NSDictionary * dict = dic.copy;
  1294. [ChatsStore.shareInstance reciveMsg:dict];//预先展示聊天窗信息
  1295. [dic setObject:[NSNull null] forKey:@"id"];
  1296. }
  1297. NSDictionary *sendInfo = @{
  1298. @"code":@"2",
  1299. @"message":dic,
  1300. };
  1301. NSError *error;
  1302. // NSLog(@"resendMsg---------:%@",msg[@"localtime"]);
  1303. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1304. if (!jsonData) {
  1305. NSLog(@"Got an error: %@", error);
  1306. } else {
  1307. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1308. [GWebSocket.shareInstance sendMsg:jsonString];
  1309. }
  1310. }
  1311. #pragma mark 上传图片
  1312. -(void)showImagePicker:(NSInteger)state{
  1313. NSLog(@"showImagePicker");
  1314. PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
  1315. if (status == PHAuthorizationStatusAuthorized) {
  1316. // 已经授权,可以访问相册
  1317. } else {
  1318. // 未授权,请求授权
  1319. [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1320. if (status == PHAuthorizationStatusAuthorized) {
  1321. // 用户授权了访问相册
  1322. // 在这里执行相册相关的操作
  1323. } else {
  1324. // 用户拒绝授权
  1325. // 可以提供一些用户指导或提示信息
  1326. return;
  1327. }
  1328. }];
  1329. }
  1330. PHPickerConfiguration *config = [[PHPickerConfiguration alloc] init];
  1331. if(state==1){
  1332. config.filter = [PHPickerFilter imagesFilter]; // 可以设置过滤器,例如只选择图片或视频等
  1333. }
  1334. else if(state==2){
  1335. config.filter = [PHPickerFilter videosFilter]; // 可以设置过滤器,例如只选择图片或视频等
  1336. }
  1337. config.selectionLimit = 9; // 限制选择数量,设置为1表示只能选择一张图片
  1338. config.preferredAssetRepresentationMode = PHPickerConfigurationAssetRepresentationModeCurrent;
  1339. PHPickerViewController *imagePicker = [[PHPickerViewController alloc] initWithConfiguration:config];
  1340. imagePicker.delegate = self; // 设置代理以接收选择结果
  1341. [self presentViewController:imagePicker animated:YES completion:nil];
  1342. }
  1343. - (void)picker:(PHPickerViewController *)picker didFinishPicking:(NSArray<PHPickerResult *> *)results {
  1344. [picker dismissViewControllerAnimated:YES completion:nil]; // 关闭选择器视图控制器
  1345. if (results.count == 0) {
  1346. return;
  1347. }
  1348. NSMutableArray * fileArray = [NSMutableArray array];
  1349. for (PHPickerResult * result in results) {
  1350. NSItemProvider *itemProvider = result.itemProvider;
  1351. NSString *typeIdentifier = result.itemProvider.registeredTypeIdentifiers.firstObject;
  1352. if ([result.itemProvider canLoadObjectOfClass:[UIImage class]]) {
  1353. [result.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
  1354. if (error) {
  1355. NSLog(@"Error loading file: %@", error);
  1356. return;
  1357. }
  1358. NSLog(@"File URL: %@", url); // 这里就是文件的 URL 路径
  1359. // 你可以使用这个 URL 进行进一步处理,例如读取文件内容或者将其复制到应用沙盒中的其他位置。
  1360. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1361. if(savedPath.length>0){
  1362. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1363. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1364. model.fileURL = fileUrl;
  1365. model.filePath = savedPath;
  1366. [fileArray addObject:model];
  1367. if (fileArray.count==results.count) {
  1368. dispatch_async(dispatch_get_main_queue(), ^{
  1369. [self handleMediaData:fileArray];
  1370. });
  1371. }
  1372. }
  1373. else{
  1374. NSLog(@"-----找不到文件------");
  1375. }
  1376. }];
  1377. }else{
  1378. [result.itemProvider loadFileRepresentationForTypeIdentifier:typeIdentifier completionHandler:^(NSURL * _Nullable url, NSError * _Nullable error) {
  1379. if (error) {
  1380. NSLog(@"Error loading file: %@", error);
  1381. return;
  1382. }
  1383. NSLog(@"File URL: %@", url); // 这里就是文件的 URL 路径
  1384. // 你可以使用这个 URL 进行进一步处理,例如读取文件内容或者将其复制到应用沙盒中的其他位置。
  1385. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1386. if(savedPath.length>0){
  1387. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1388. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1389. model.fileURL = fileUrl;
  1390. model.filePath = savedPath;
  1391. [fileArray addObject:model];
  1392. if (fileArray.count==results.count) {
  1393. dispatch_async(dispatch_get_main_queue(), ^{
  1394. [self handleMediaData:fileArray];
  1395. });
  1396. }
  1397. }
  1398. else{
  1399. NSLog(@"-----找不到文件------");
  1400. }
  1401. }];
  1402. }
  1403. }
  1404. }
  1405. #pragma mark - 写入方法
  1406. - (NSString *)saveImageToSandbox:(UIImage *)image {
  1407. // 获取沙盒Documents目录
  1408. NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1409. // 生成唯一文件名
  1410. NSString *fileName = [NSString stringWithFormat:@"%@.jpg", [[NSUUID UUID] UUIDString]];
  1411. NSString *filePath = [documentsPath stringByAppendingPathComponent:fileName];
  1412. // 将图片转换为JPEG格式数据
  1413. NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
  1414. // 写入文件
  1415. BOOL success = [imageData writeToFile:filePath atomically:YES];
  1416. if (success) {
  1417. NSLog(@"图片保存成功,路径: %@", filePath);
  1418. return filePath;
  1419. } else {
  1420. NSLog(@"图片保存失败");
  1421. return nil;
  1422. }
  1423. }
  1424. - (NSString *)saveVideoDataToDocumentsDirectory:(NSData *)videoData {
  1425. // 1. 生成唯一文件名
  1426. NSString *fileName = [NSString stringWithFormat:@"%@.mp4", [[NSUUID UUID] UUIDString]];
  1427. // 2. 获取Documents目录路径
  1428. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  1429. NSString *documentsDirectory = [paths firstObject];
  1430. NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
  1431. // 3. 写入数据
  1432. NSError *writeError;
  1433. [videoData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
  1434. if (writeError) {
  1435. NSLog(@"Error writing video data: %@", writeError.localizedDescription);
  1436. return nil;
  1437. }
  1438. return filePath;
  1439. }
  1440. - (NSString *)saveFileToDocumentsDirectory:(NSURL *)fromePath {
  1441. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1442. NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:fromePath.lastPathComponent]; // 目标文件路径
  1443. NSFileManager *fileManager = [NSFileManager defaultManager];
  1444. NSError *error = nil;
  1445. if([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]){
  1446. return destinationPath;
  1447. }
  1448. else{
  1449. BOOL success = [fileManager copyItemAtPath:fromePath.path toPath:destinationPath error:&error];
  1450. if (success) {
  1451. NSLog(@"文件成功复制到本地");
  1452. return destinationPath;
  1453. } else {
  1454. NSLog(@"文件复制失败: %@", error.localizedDescription);
  1455. return @"";
  1456. }
  1457. }
  1458. }
  1459. #pragma mark -文件选择和处理
  1460. -(void)showfilePicker{
  1461. // 创建文档选择器
  1462. NSArray<UTType *> *contentTypes = @[UTTypeItem];
  1463. UIDocumentPickerViewController *documentPicker = [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:contentTypes
  1464. asCopy:YES];
  1465. documentPicker.allowsMultipleSelection = YES;
  1466. documentPicker.delegate = self;
  1467. [self presentViewController:documentPicker animated:YES completion:nil];
  1468. }
  1469. #pragma mark - 文件选择回调 UIDocumentPickerDelegate
  1470. - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
  1471. // 用户选择了一个或多个文件,处理这些文件
  1472. if (urls.count > 9) {
  1473. //选择文件最多 9 个
  1474. [MBProgressHUD showWithText:@"一次最多上傳 9 個檔案"];
  1475. }
  1476. NSMutableArray * fileArray = [NSMutableArray array];
  1477. for (NSURL * url in urls) {
  1478. if ([urls indexOfObject:url] > 9) {
  1479. break;
  1480. }
  1481. NSLog(@"url:%@",url);
  1482. NSString *savedPath = [self saveFileToDocumentsDirectory:url];
  1483. if(savedPath.length>0){
  1484. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1485. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1486. model.fileURL = fileUrl;
  1487. model.filePath = savedPath;
  1488. [fileArray addObject:model];
  1489. }
  1490. }
  1491. dispatch_async(dispatch_get_main_queue(), ^{
  1492. [self handleMediaData:fileArray];
  1493. });
  1494. }
  1495. #pragma mark 批量处理文件上传
  1496. - (void)handleMediaData:(NSArray *)mediaArray{
  1497. // NSMutableArray * tempArray = [NSMutableArray array];
  1498. NSArray *sorArray = [self fileArraysort:mediaArray];
  1499. for (ChatFileModel * model in sorArray) {
  1500. NSString *strtime = [self getLocalTime];
  1501. [self uploadFile:[NSString stringWithFormat:@"%@",model.fileURL] fpath:model.filePath state:1 act:1 localtime:strtime];
  1502. [self OSSuploadFile:model thrid:strtime];
  1503. }
  1504. }
  1505. -(void)OSSuploadFile:(ChatFileModel *)model thrid:(NSString *)strtime{
  1506. NSString * tempChatId = self.chatId.mutableCopy;
  1507. [ChatsStore shareInstance].chatId = tempChatId;
  1508. [ChatsStore shareInstance].delegate = self;
  1509. // 断点续传
  1510. [OSSManager.sharedManager asyncResumableUploadFile:model.fileURL.lastPathComponent localFilePath:model.filePath thrid:strtime];
  1511. }
  1512. -(void)stateChange:(NSDictionary *)changeMsg{
  1513. dispatch_main_async_safe(^{
  1514. NSString *loacaltime = changeMsg[@"thrid"];
  1515. NSString *pcent = changeMsg[@"pcent"];
  1516. NSString *state = changeMsg[@"state"];
  1517. NSLog(@"uploadProgress: %@",pcent);
  1518. if([state isEqualToString:@"1"]){
  1519. [self Ossupdatajidu:loacaltime uploadProgress:pcent.intValue];
  1520. }
  1521. })
  1522. }
  1523. -(void)resendFile:(ChatMessageModel *)msg{
  1524. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)msg.localtime];
  1525. NSString *loaclFile = [NSString stringWithFormat:@"%@",msg.localurl];
  1526. if(![[NSFileManager defaultManager] fileExistsAtPath:loaclFile]){
  1527. [MBProgressHUD showWithText:@"文件不存在,請重新選擇"];
  1528. return;
  1529. }
  1530. NSURL * fileUrl = [NSURL fileURLWithPath:loaclFile];
  1531. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileUrl];
  1532. model.fileURL = fileUrl;
  1533. model.filePath = loaclFile;
  1534. [self OSSuploadFile:model thrid:strtime];
  1535. }
  1536. -(void)uploadFile:(NSString *)url fpath:(NSString *)path state:(NSInteger)state act:(NSInteger)act localtime:(NSString *)localtime{
  1537. NSURL *filePath;
  1538. if([url containsString:@"http"]){
  1539. filePath=[NSURL URLWithString:url]; //
  1540. }
  1541. else{
  1542. NSString *filestr = [[OSSManager sharedManager] fullUploadURLByAppendPath:url];
  1543. filePath=[NSURL URLWithString:filestr]; //
  1544. }
  1545. NSString *content=@"【文件】";
  1546. NSString *messageType=MessageType_file;
  1547. NSDictionary *extend;
  1548. if(state==1){//文件类消息
  1549. NSString *kzm = filePath.pathExtension;
  1550. kzm=[kzm lowercaseString];
  1551. if([kzm isEqualToString:@"png"]||[kzm isEqualToString:@"jpg"]||[kzm isEqualToString:@"jpeg"]||[kzm isEqualToString:@"bmp"]){
  1552. content=@"【图片】";
  1553. messageType=MessageType_image;
  1554. }
  1555. if([kzm isEqualToString:@"mp4"]||[kzm isEqualToString:@"avi"]||[kzm isEqualToString:@"wmv"]||[kzm isEqualToString:@"mov"]||[kzm isEqualToString:@"mpeg"]){
  1556. content=@"【视频】";
  1557. messageType=MessageType_video;
  1558. }
  1559. }
  1560. content= [CryptoAES.shareInstance encryptStringL:content];
  1561. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1562. NSDictionary *msgt;
  1563. NSDictionary *msgd;
  1564. if(act==1){
  1565. extend=@{
  1566. @"url":@"",
  1567. @"fileName":filePath.lastPathComponent,
  1568. @"localurl":path,
  1569. @"fileError":[NSNumber numberWithInt:0]
  1570. };
  1571. msgt=@{
  1572. @"messageType":messageType,
  1573. @"chatId":self.chatId,
  1574. @"fromId":self.userId,
  1575. @"fromName":self.username,
  1576. @"fromAvatar":self.useravatar,
  1577. @"content":content,
  1578. @"type":type,
  1579. @"reSend": [NSNumber numberWithBool:false],
  1580. @"extend": extend,
  1581. @"localtime":localtime,
  1582. @"timestamp":localtime,
  1583. @"mine":[NSNumber numberWithBool:YES],
  1584. @"id":localtime,
  1585. };
  1586. msgd=@{
  1587. @"messageType":messageType,
  1588. @"chatId":self.chatId,
  1589. @"fromId":self.userId,
  1590. @"fromName":self.username,
  1591. @"fromAvatar":self.useravatar,
  1592. @"content":content,
  1593. @"type":type,
  1594. @"reSend": [NSNumber numberWithBool:false],
  1595. @"extend": extend,
  1596. @"localtime":localtime,
  1597. @"timestamp":localtime,
  1598. @"mine":[NSNumber numberWithBool:YES],
  1599. @"id":@"",
  1600. };
  1601. NSString * tempChatId = self.chatId.mutableCopy;
  1602. [ChatsStore shareInstance].chatId = tempChatId;
  1603. [ChatsStore shareInstance].delegate = self;
  1604. [ChatsStore.shareInstance reciveMsg:msgt];
  1605. NSDictionary *sendInfo = @{
  1606. @"code":@"2",
  1607. @"message":msgd,
  1608. };
  1609. NSError *error;
  1610. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1611. if (!jsonData) {
  1612. NSLog(@"Got an error: %@", error);
  1613. } else {
  1614. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1615. // NSLog(@"%@", jsonString);
  1616. NSLog(@"----发送文件消息----%@",localtime);
  1617. //self.ismyTurn = YES;
  1618. //[GWebSocket.shareInstance sendMsg:jsonString];
  1619. }
  1620. [self movetoBotton];
  1621. }
  1622. if(act==2){
  1623. if(url){
  1624. [self uploadFileSucc:url localtime:localtime];
  1625. }
  1626. else{
  1627. }
  1628. }
  1629. }
  1630. -(void)uploadFileSucc:(NSString *)url localtime:(NSString *)localtime{
  1631. if(![url containsString:@"http"]){
  1632. url = [[OSSManager sharedManager] fullUploadURLByAppendPath:url];
  1633. }
  1634. NSURL *filePath = [NSURL URLWithString:url];
  1635. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1636. // NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1637. if(array){
  1638. if(array.count>0){
  1639. NSDictionary *msg =array[0];
  1640. NSDictionary *extend=msg[@"extend"];
  1641. NSMutableDictionary *mextend = [extend mutableCopy];
  1642. [mextend setObject:url forKey:@"url"];
  1643. [mextend setObject:filePath.lastPathComponent forKey:@"fileName"];
  1644. NSMutableDictionary *mmsg = [msg mutableCopy];
  1645. [mmsg setObject:mextend forKey:@"extend"];
  1646. [mmsg setObject:@"" forKey:@"id"];
  1647. NSDictionary *sendInfo = @{
  1648. @"code":@"2",
  1649. @"message":mmsg,
  1650. };
  1651. NSError *error;
  1652. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1653. if (!jsonData) {
  1654. NSLog(@"Got an error: %@", error);
  1655. } else {
  1656. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1657. // NSLog(@"%@", jsonString);
  1658. NSLog(@"----发送文件消息2----%@",localtime);
  1659. // self.ismyTurn = YES;
  1660. [GWebSocket.shareInstance sendMsg:jsonString];
  1661. }
  1662. }
  1663. }
  1664. } fail:^(NSString * _Nullable error) {
  1665. ;
  1666. }];
  1667. }
  1668. -(void)uploadFilefail:(NSString *)localtime{
  1669. NSLog(@"uploadFilefail----:%@",localtime);
  1670. [GDBManager.shareInstance selectLocalmsgWithLocaltime:localtime succ:^(NSArray * _Nullable array) {
  1671. NSLog(@"selectLocalmsgWithLocaltime:%@",array);
  1672. if(array){
  1673. if(array.count>0){
  1674. NSDictionary *msg =array[0];
  1675. NSString *msgtype = msg[@"messageType"];
  1676. if (([msgtype isEqualToString:MessageType_Del]||[msgtype isEqualToString:MessageType_CallBack2])) {
  1677. return;
  1678. }
  1679. NSString *strtime = [self getLocalTime];
  1680. NSDictionary *extend=msg[@"extend"];
  1681. NSMutableDictionary *mextend = [extend mutableCopy];
  1682. [mextend setObject:@"" forKey:@"url"];
  1683. [mextend setObject:@"" forKey:@"fileName"];
  1684. [mextend setObject:[NSNumber numberWithInt:1] forKey:@"fileError"];
  1685. NSMutableDictionary *mmsg = [msg mutableCopy];
  1686. [mmsg setObject:mextend forKey:@"extend"];
  1687. [mmsg setObject:strtime forKey:@"timestamp"];
  1688. [ChatsStore.shareInstance reciveMsg:mmsg];
  1689. NSDictionary *sendInfo = @{
  1690. @"code":@"2",
  1691. @"message":mmsg,
  1692. };
  1693. NSError *error;
  1694. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1695. if (!jsonData) {
  1696. NSLog(@"Got an error: %@", error);
  1697. } else {
  1698. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1699. // NSLog(@"%@", jsonString);
  1700. NSLog(@"----发送文件失败消息2----%@",localtime);
  1701. // self.ismyTurn = YES;
  1702. //[GWebSocket.shareInstance sendMsg:jsonString];
  1703. }
  1704. }
  1705. }
  1706. } fail:^(NSString * _Nullable error) {
  1707. ;
  1708. }];
  1709. }
  1710. -(void)Ossupdatajidu:(NSString *)localtime uploadProgress:(NSInteger )Progress{
  1711. [self updateProgress:Progress localtime:localtime];
  1712. }
  1713. - (void)updateProgress:(NSInteger )Progress localtime:(NSString *)localtime {
  1714. for (chatCellView *cell in self._tableView.visibleCells) {
  1715. ChatMessageModel *message = cell.messageModel;
  1716. if(message.localtime==localtime.integerValue){
  1717. [cell fileUploadProgressDidChanged:Progress localtime:localtime.integerValue];
  1718. }
  1719. }
  1720. }
  1721. #pragma mark 录音发送
  1722. -(void)longTarget{
  1723. NSLog(@"longTarget----------");
  1724. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeGreen).CGColor;
  1725. [_AVRecordBt setTitle:@" 松开 发送" forState:UIControlStateNormal];
  1726. NSDate *now = [NSDate date];
  1727. NSTimeInterval trt = [now timeIntervalSince1970];
  1728. NSInteger time = trt*1000;
  1729. _AudiofileName = [NSString stringWithFormat:@"%ld.mp4",(long)time];
  1730. _AudiofilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:_AudiofileName];
  1731. NSError *error = nil;
  1732. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  1733. [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
  1734. //[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
  1735. [audioSession setActive:YES error:nil];
  1736. NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  1737. [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatMPEG4AAC] forKey:AVFormatIDKey];
  1738. [recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; //采样率
  1739. [recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
  1740. [recordSetting setValue:[NSNumber numberWithInt: AVAudioQualityMedium] forKey:AVEncoderAudioQualityKey];
  1741. NSURL *fileURL = [NSURL fileURLWithPath:_AudiofilePath];
  1742. _recorder = [[AVAudioRecorder alloc] initWithURL:fileURL settings:recordSetting error:&error];
  1743. if (error) {
  1744. NSLog(@"Error creating recorder: %@", error);
  1745. } else {
  1746. [_recorder prepareToRecord];
  1747. [_recorder record];
  1748. }
  1749. _rcdL=0;
  1750. self.heatBeat = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(heartbeatAction) userInfo:nil repeats:YES];
  1751. [self.heatBeat setFireDate:[NSDate distantPast]];
  1752. [[NSRunLoop currentRunLoop] addTimer:_heatBeat forMode:NSRunLoopCommonModes];
  1753. }
  1754. -(void)heartbeatAction{
  1755. if(_rcdL==60){
  1756. [_recorder stop];
  1757. _recorder=nil;
  1758. return;
  1759. }
  1760. _rcdL=_rcdL+1;
  1761. }
  1762. -(void)UpInside{
  1763. _AVRecordBt.layer.backgroundColor = globalColor(GCTypeDark2).CGColor;
  1764. [_AVRecordBt setTitle:@" 按住 说话" forState:UIControlStateNormal];
  1765. NSLog(@"UpInside----------");
  1766. [_recorder stop];
  1767. _recorder=nil;
  1768. NSURL *yuanfileURL = [NSURL fileURLWithPath:_AudiofilePath];
  1769. if(_rcdL<2){//语音太短
  1770. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1771. [self.heatBeat invalidate];
  1772. self.heatBeat = nil;
  1773. [MBProgressHUD showWithText:@"語音太短"];
  1774. return;
  1775. }
  1776. NSLog(@"_AudiofilePath:%@",_AudiofilePath);
  1777. NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  1778. NSString *destinationPath = [documentsDirectory stringByAppendingPathComponent:yuanfileURL.lastPathComponent]; // 目标文件路径
  1779. NSFileManager *fileManager = [NSFileManager defaultManager];
  1780. NSError *error = nil;
  1781. BOOL success = [fileManager copyItemAtPath:_AudiofilePath toPath:destinationPath error:&error];
  1782. if (success) {
  1783. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1784. NSLog(@"文件成功复制到本地");
  1785. } else {
  1786. [[NSFileManager defaultManager] removeItemAtURL:yuanfileURL error:nil];
  1787. NSLog(@"文件复制失败: %@", error.localizedDescription);
  1788. [MBProgressHUD showWithText:@"語音發送異常請重試"];
  1789. return;
  1790. }
  1791. NSLog(@"destinationPath:%@",destinationPath);
  1792. NSURL *fileURL = [NSURL fileURLWithPath:destinationPath];
  1793. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:fileURL];
  1794. model.fileURL = fileURL;
  1795. model.filePath = destinationPath;
  1796. NSString *strtime = [self getLocalTime];
  1797. [self sendYuyinMsg:model.fileURL.lastPathComponent filePth:destinationPath localtime:strtime state:0];
  1798. [self OSSuploadFile:model thrid:strtime];
  1799. [self.heatBeat invalidate];
  1800. self.heatBeat = nil;
  1801. }
  1802. -(void)sendYuyinMsg:(NSString *)fileName filePth:(NSString *)filePtah localtime:(NSString *)loacaltime state:(NSInteger)index{
  1803. NSString *filePath;
  1804. if([fileName containsString:@"http"]){
  1805. filePath=fileName;
  1806. }
  1807. else{
  1808. filePath = [[OSSManager sharedManager] fullUploadURLByAppendPath:fileName];
  1809. }
  1810. NSString *content=@"【语音】";
  1811. NSString *messageType=[NSString stringWithFormat:@"%@",MessageType_voice];
  1812. content= [CryptoAES.shareInstance encryptStringL:content];
  1813. NSString *type = [NSString stringWithFormat:@"%ld",(long)self.type];
  1814. NSString *localId =loacaltime;
  1815. if(index==1){
  1816. localId=@"";
  1817. }
  1818. NSDictionary *dic =@{
  1819. @"id":localId,
  1820. @"messageType":messageType,
  1821. @"chatId":self.chatId,
  1822. @"fromId":self.userId,
  1823. @"fromName":self.username,
  1824. @"fromAvatar":self.useravatar,
  1825. @"reSend":[NSNumber numberWithBool:false],
  1826. @"content":content,
  1827. @"type":type,
  1828. @"localtime":loacaltime,
  1829. @"timestamp":loacaltime,
  1830. @"mine":[NSNumber numberWithBool:YES],
  1831. @"extend":@{
  1832. @"url":@"",
  1833. @"time":[NSString stringWithFormat:@"%ld",self->_rcdL],
  1834. @"localurl":filePtah
  1835. }
  1836. };
  1837. if(index==0){
  1838. [ChatsStore.shareInstance reciveMsg:dic];
  1839. }
  1840. NSDictionary *sendInfo = @{
  1841. @"code":@"2",
  1842. @"message":dic,
  1843. };
  1844. NSError *error;
  1845. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  1846. if (!jsonData) {
  1847. NSLog(@"Got an error: %@", error);
  1848. } else {
  1849. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1850. NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  1851. NSLog(@"----发送语音----");
  1852. if(index==1){
  1853. [GWebSocket.shareInstance sendMsg:jsonString];
  1854. }
  1855. }
  1856. }
  1857. -(void)showWebRtcVidio:(NSInteger)state{
  1858. if(self.type==1){
  1859. [MBProgressHUD showWithText:@"群聊暂时不支持该功能"];
  1860. return;
  1861. }
  1862. BOOL audioOnly=YES;
  1863. if(state==4){
  1864. audioOnly = YES;
  1865. }
  1866. else{
  1867. audioOnly = NO;
  1868. }
  1869. [[AppDelegate sharedInstance] startJSCall:self.chatId room:@"" isCaller:YES audioOnly:audioOnly];
  1870. }
  1871. #pragma mark take photo or video
  1872. - (void)takePhoto{
  1873. // 检查设备是否支持相机
  1874. if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
  1875. CameraViewController *cameraVC = [[CameraViewController alloc] init];
  1876. cameraVC.modalPresentationStyle = UIModalPresentationFullScreen;
  1877. [self presentViewController:cameraVC animated:YES completion:nil];
  1878. weakSelf(self);
  1879. cameraVC.takePhotoFinishBlock = ^(UIImage * _Nonnull image) {
  1880. // 保存图片到本地
  1881. NSString *savedPath = [self saveImageToSandbox:image];
  1882. dispatch_async(dispatch_get_main_queue(), ^{
  1883. // 4. 更新UI或处理保存结果
  1884. if (savedPath) {
  1885. NSURL * fileUrl = [NSURL fileURLWithPath:savedPath];
  1886. NSString *strtime = [self getLocalTime];
  1887. //展示自己发的本地图片
  1888. [self uploadFile:[NSString stringWithFormat:@"%@",fileUrl] fpath:savedPath state:1 act:1 localtime:strtime];
  1889. [FileNetApi uploadWithFilePath:fileUrl thrid:strtime progress:^(NSString *_Nullable thrid,NSProgress * _Nullable uploadProgress) {
  1890. } succ:^(int code,NSString *_Nullable thrid, NSDictionary * _Nullable dis) {
  1891. NSString *reCode =dis[@"code"];
  1892. if(reCode.intValue==200){
  1893. NSLog(@"上传成功:%@",dis[@"url"]);
  1894. [weakself uploadFile:dis[@"url"] fpath:savedPath state:1 act:2 localtime:thrid];
  1895. }
  1896. else{
  1897. NSLog(@"上传失败");
  1898. }
  1899. } fail:^(NSString *_Nullable thrid,NSError * _Nonnull error) {
  1900. NSLog(@"上传失败");
  1901. }];
  1902. } else {
  1903. NSLog(@"图片保存失败");
  1904. }
  1905. });
  1906. };
  1907. cameraVC.takeVideoFinishBlock = ^(NSURL * _Nonnull videoUrl) {
  1908. ChatFileModel * model = [[ChatFileModel alloc] initWithURL:videoUrl];
  1909. // ChatFileModel * model = [[ChatFileModel alloc] initWithName:[FileInfoUtils getFileNameWithURL:videoUrl] size:[FileInfoUtils getFileSizeStringWithURL:videoUrl error:nil] isOversize:[FileInfoUtils isFileGreaterThan100MB:videoUrl error:nil]];
  1910. model.fileURL = videoUrl;
  1911. model.filePath = [videoUrl path];
  1912. // [weakself handleMediaData:@[model]];
  1913. dispatch_async(dispatch_get_main_queue(), ^{
  1914. [weakself handleMediaData:@[model]];
  1915. });
  1916. };
  1917. } else {
  1918. NSLog(@"设备不支持相机");
  1919. [MBProgressHUD showWithText:@"设备不支持相机"];
  1920. }
  1921. }
  1922. #pragma mark menu Actoin
  1923. - (void)copyMessageContent:(NSString *)content{
  1924. UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
  1925. pasteboard.string = content;
  1926. [MBProgressHUD showWithText:NSLocalizedString(@"cellact-copysuccese", @"")];
  1927. }
  1928. - (void)addFavorites:(NSDictionary *)dict{
  1929. NSLog(@"----收藏的消息:%@",dict);
  1930. NSMutableDictionary * favoritesDict = [dict mutableCopy];
  1931. NSString *extend = @"";
  1932. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:favoritesDict[@"extend"] options:0 error:nil];
  1933. if (!jsonData) {
  1934. NSLog(@"Got an error:");
  1935. } else {
  1936. extend = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  1937. }
  1938. [favoritesDict setValue:extend forKey:@"extend"];
  1939. [UserNetApi addFavorites:favoritesDict succ:^(int code, NSDictionary * _Nullable res) {
  1940. // NSLog(@"------result:%@",res);
  1941. NSString *ecode = res[@"code"];
  1942. if(ecode.intValue==200){
  1943. if ([res jk_hasKey:@"msg"] && ![res[@"msg"] isKindOfClass:NSNull.class]) {
  1944. [MBProgressHUD showWithText:res[@"msg"]];
  1945. }
  1946. }
  1947. else{
  1948. [MBProgressHUD showWithText:NSLocalizedString(@"AppLock_fail", @"收藏失败")];
  1949. }
  1950. } fail:^(NSError * _Nonnull error) {
  1951. NSLog(@"error:%@",error);
  1952. }];
  1953. }
  1954. - (void)deleteMyMsg:(NSDictionary *)dict{
  1955. NSMutableDictionary * msgDict = [NSMutableDictionary dictionaryWithDictionary:dict];
  1956. [msgDict setValue:@"12" forKey:@"messageType"];
  1957. [msgDict setValue:@"删除了一条消息" forKey:@"content"];
  1958. [ChatsStore.shareInstance reciveMsg:msgDict];
  1959. [ChatListStore.shareInstance reciveMsg:msgDict];
  1960. // [self cutDataSource:@[dict]];
  1961. // [ChatsStore.shareInstance deleteMyLocalMsg:dict];
  1962. }
  1963. //转发
  1964. - (void)forwardMsg:(NSArray *)msgArray isMultiple:(BOOL)isMultiple{
  1965. // [MBProgressHUD showWithText:@"功能待完善"];
  1966. // return;
  1967. ForwardViewController * forwordVc = [[ForwardViewController alloc] init];
  1968. forwordVc.fromChatId = self.chatId;
  1969. forwordVc.isMultiple = isMultiple;
  1970. forwordVc.msgArray = msgArray;
  1971. forwordVc.userName = self.username;
  1972. forwordVc.userAvatar = self.useravatar;
  1973. UINavigationController * navi = [[UINavigationController alloc] initWithRootViewController:forwordVc];
  1974. navi.modalPresentationStyle = UIModalPresentationFullScreen;
  1975. [self presentViewController:navi animated:YES completion:nil];
  1976. }
  1977. - (void)batchProcess{
  1978. self.isBatchMode = YES;
  1979. [UIView animateWithDuration:0.5 animations:^{
  1980. self.batchView.frame = CGRectMake(0, SCREEN_HEIGHT-SCREEN_X_BTM-64, SCREEN_WIDTH, SCREEN_X_BTM+64);
  1981. }];
  1982. weakSelf(self);
  1983. __weak typeof(self.batchView) weakView = self.batchView;
  1984. self.batchView.indexOfBatchClicked = ^(NSInteger index) {
  1985. weakself.isBatchMode = NO;
  1986. if (index == 0) {//关闭
  1987. }else if (index == 1) {
  1988. //合并
  1989. if (weakself.forwordMsgArray.count == 0) {
  1990. [MBProgressHUD showWithText:@"请选择转发的消息"];
  1991. return;
  1992. }
  1993. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  1994. [weakself forwardMsg:tempForwardArray isMultiple:YES];
  1995. [weakself.forwordMsgArray removeAllObjects];
  1996. }else if (index == 2) {
  1997. //逐条
  1998. if (weakself.forwordMsgArray.count == 0) {
  1999. [MBProgressHUD showWithText:@"请选择转发的消息"];
  2000. return;
  2001. }
  2002. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  2003. [weakself forwardMsg:tempForwardArray isMultiple:NO];
  2004. [weakself.forwordMsgArray removeAllObjects];
  2005. }else if (index == 3) {
  2006. //删除
  2007. if (weakself.forwordMsgArray.count == 0) {
  2008. [MBProgressHUD showWithText:@"请选择删除的消息"];
  2009. return;
  2010. }
  2011. NSMutableArray * tempForwardArray = weakself.forwordMsgArray.mutableCopy;
  2012. for (NSDictionary * msg in tempForwardArray) {
  2013. [weakself deleteMyMsg:msg];
  2014. }
  2015. [weakself.forwordMsgArray removeAllObjects];
  2016. }
  2017. [UIView animateWithDuration:0.5 animations:^{
  2018. weakView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_X_BTM+64);
  2019. }];
  2020. [weakself.forwordMsgArray removeAllObjects];
  2021. [weakself._tableView reloadData];
  2022. };
  2023. [self._tableView reloadData];
  2024. }
  2025. - (void)messageCallback:(NSDictionary *)dict{
  2026. // [MBProgressHUD showWithText:@"功能待完善"];
  2027. // return;
  2028. NSMutableDictionary * msgDict = [NSMutableDictionary dictionaryWithDictionary:dict];
  2029. NSDate *now = [NSDate date];
  2030. NSTimeInterval trt = [now timeIntervalSince1970];
  2031. NSInteger time = trt*1000;
  2032. [msgDict setValue:@"11" forKey:@"messageType"];
  2033. [msgDict setValue:@"撤回了一条消息" forKey:@"content"];
  2034. [msgDict setValue:[NSString stringWithFormat:@"%ld",time] forKey:@"id"];
  2035. // self.msgList = [ChatsStore.shareInstance replaydisData:[msgDict copy] inarray:self.msgList];
  2036. [ChatsStore.shareInstance reciveMsg:[msgDict copy]];//预先展示聊天窗信息
  2037. [ChatListStore.shareInstance reciveMsg:msgDict];
  2038. NSLog(@"撤回---:%@",msgDict);
  2039. NSDictionary *sendInfo = @{
  2040. @"code":@"2",
  2041. @"message":msgDict,
  2042. };
  2043. NSError *error;
  2044. NSData *jsonData = [NSJSONSerialization dataWithJSONObject:sendInfo options:0 error:&error];
  2045. if (!jsonData) {
  2046. NSLog(@"Got an error: %@", error);
  2047. } else {
  2048. NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
  2049. //NSLog(@"%@", jsonString); // 输出: {"name":"John","age":25}
  2050. NSLog(@"----撤回消息----");
  2051. [GWebSocket.shareInstance sendMsg:jsonString];
  2052. }
  2053. [self ifisfileMsg:dict];
  2054. }
  2055. //撤回文件消息,同时取消上传
  2056. -(void)ifisfileMsg:(NSDictionary *)msg{
  2057. NSString *messageType = msg[@"messageType"];
  2058. if ([messageType isEqualToString:MessageType_file]||[messageType isEqualToString:MessageType_video]||[messageType isEqualToString:MessageType_image]) {
  2059. NSString *lcotime = msg[@"localtime"];
  2060. [FileNetApi stopUploadTanck:lcotime];
  2061. }
  2062. }
  2063. - (void)quoteMessage:(ChatMessageModel *)message{
  2064. if (self.isQuoteMessage) {
  2065. self.quoteView.model = message;
  2066. [self.inputView becomeFirstResponder];
  2067. return;
  2068. }
  2069. self.isQuoteMessage = YES;
  2070. self.quoteView.model = message;
  2071. self.quoteView.hidden = NO;
  2072. CGRect buttonViewFrame = self.bottonView.frame;
  2073. self.bottonView.frame = CGRectMake(buttonViewFrame.origin.x, buttonViewFrame.origin.y-kQuoteViewHeight, buttonViewFrame.size.width, buttonViewFrame.size.height+kQuoteViewHeight);
  2074. // CGRect inputViewFrame = self.inputView.frame;
  2075. // self.inputView.frame = CGRectMake(inputViewFrame.origin.x, inputViewFrame.origin.y-kQuoteViewHeight, inputViewFrame.size.width, inputViewFrame.size.height);
  2076. CGRect audioBtnFrame = self.yuyinctr.frame;
  2077. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y-kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  2078. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  2079. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y-kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  2080. CGRect sendBtnFrame = self.fasngBt.frame;
  2081. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y-kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  2082. [self.inputView becomeFirstResponder];
  2083. }
  2084. - (void)closeQuoteView{
  2085. self.isQuoteMessage = NO;
  2086. self.quoteView.hidden = YES;
  2087. CGRect buttonViewFrame = self.bottonView.frame;
  2088. self.bottonView.frame = CGRectMake(buttonViewFrame.origin.x, buttonViewFrame.origin.y+kQuoteViewHeight, buttonViewFrame.size.width, buttonViewFrame.size.height-kQuoteViewHeight);
  2089. self.inputView.frame = CGRectMake(54, 10, self.view.frame.size.width - 180, 40);
  2090. CGRect audioBtnFrame = self.yuyinctr.frame;
  2091. self.yuyinctr.frame = CGRectMake(audioBtnFrame.origin.x, audioBtnFrame.origin.y+kQuoteViewHeight, audioBtnFrame.size.height, audioBtnFrame.size.height);
  2092. CGRect moreFunctionBtnFrame = self.gengduoBt.frame;
  2093. self.gengduoBt.frame = CGRectMake(moreFunctionBtnFrame.origin.x, moreFunctionBtnFrame.origin.y+kQuoteViewHeight, moreFunctionBtnFrame.size.width, moreFunctionBtnFrame.size.height);
  2094. CGRect sendBtnFrame = self.fasngBt.frame;
  2095. self.fasngBt.frame = CGRectMake(sendBtnFrame.origin.x, sendBtnFrame.origin.y+kQuoteViewHeight, sendBtnFrame.size.width, sendBtnFrame.size.height);
  2096. CGRect tframe = self._tableView.frame;
  2097. tframe.size.height = self.bottonView.frame.origin.y-tframe.origin.y;
  2098. self._tableView.frame = tframe;
  2099. [self movetoBotton];
  2100. }
  2101. - (void)cutDataSource:(NSArray *)msgArray{
  2102. NSMutableArray * indexPathArray = [NSMutableArray array];
  2103. NSMutableArray * tempArray = [NSMutableArray arrayWithArray:self.messageArray];
  2104. for (NSDictionary * msg in msgArray) {
  2105. for (ChatMessageModel * message in tempArray) {
  2106. if ([message.formerMessage[@"id"] isEqualToString:msg[@"id"]]) {
  2107. NSInteger index = [tempArray indexOfObject:message];
  2108. [self.messageArray removeObjectAtIndex:index];
  2109. NSIndexPath *deleteIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
  2110. [indexPathArray addObject:deleteIndexPath];
  2111. }
  2112. }
  2113. }
  2114. [CATransaction begin];
  2115. [CATransaction setDisableActions:YES];
  2116. [self._tableView beginUpdates];
  2117. [self._tableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
  2118. [self._tableView endUpdates];
  2119. [CATransaction commit];
  2120. }
  2121. #pragma mark @相关
  2122. - (void)showAtMemberView{
  2123. ChatAtMemberView * atView = [[ChatAtMemberView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-200)];
  2124. atView.memberArray = [ChatsStore shareInstance].groupUserList;
  2125. if (self.groupInfo && [self.groupInfo[@"master"] isEqualToString:self.userId]) {
  2126. atView.isGroupMaster = YES;
  2127. }else{
  2128. atView.isGroupMaster = NO;
  2129. }
  2130. //[atView jk_setRoundedCorners:UIRectCornerTopLeft|UIRectCornerTopRight radius:10.f];
  2131. PopupView * popup = [[PopupView alloc] init];
  2132. popup.customView = atView;
  2133. popup.position = PopupPositionBottom;
  2134. popup.animationType = PopupAnimationTypeFromBottom; // 从下往上动画
  2135. popup.dismissOnBackgroundTap = YES; // 点击背景关闭
  2136. popup.containerType = PopupContainerTypeWindow; // 添加到window
  2137. [popup showInView:self.view];
  2138. weakSelf(self);
  2139. atView.closeAtViewBlock = ^{
  2140. [popup dismiss];
  2141. };
  2142. atView.atMembersBlock = ^(NSArray * _Nonnull selectedArray) {
  2143. [popup dismiss];
  2144. for (int i = 0; i < selectedArray.count; i++) {
  2145. NSDictionary * member = selectedArray[i];
  2146. [weakself.inputView insertText:[NSString stringWithFormat:@"@%@ ",member[@"name"]]];
  2147. }
  2148. [weakself.atSomeoneArray addObjectsFromArray:selectedArray];
  2149. [weakself.inputView becomeFirstResponder];
  2150. };
  2151. atView.atSingleMemberBlock = ^(NSDictionary * _Nonnull member) {
  2152. [popup dismiss];
  2153. [weakself.inputView insertText:[NSString stringWithFormat:@"@%@ ",member[@"name"]]];
  2154. [weakself.atSomeoneArray addObject:member];
  2155. [weakself.inputView becomeFirstResponder];
  2156. };
  2157. atView.atEveryoneBlock = ^{
  2158. [popup dismiss];
  2159. [weakself.inputView insertText:@"@所有人 "];
  2160. [weakself.inputView becomeFirstResponder];
  2161. };
  2162. }
  2163. -(void)removeAtList:(NSInteger)index{
  2164. if(self.atSomeoneArray.count>index){
  2165. [self.atSomeoneArray removeObjectAtIndex:index];
  2166. [self textViewDidChange:_inputView];
  2167. }
  2168. }
  2169. #pragma mark 文件大小排序
  2170. -(NSArray *_Nullable)fileArraysort:(NSArray *_Nullable)array{
  2171. NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(ChatFileModel *obj1, ChatFileModel *obj2) {
  2172. if(obj1.bySize<obj2.bySize){
  2173. return NSOrderedAscending;
  2174. }
  2175. else if(obj1.bySize==obj2.bySize){
  2176. return NSOrderedSame;
  2177. }
  2178. else{
  2179. return NSOrderedDescending;
  2180. }
  2181. }];
  2182. return sortedArray;
  2183. }
  2184. #pragma mark 其他聊天室的消息弹窗
  2185. - (void)othersChatMessageAlert:(NSNotification *)notification {
  2186. // NSLog(@"othersChatMessageAlert---1");
  2187. if ([self isViewLoaded] && self.view.window) {
  2188. NSDictionary * msgDict = notification.object;
  2189. NSMutableDictionary * mutablemsg = msgDict.mutableCopy;
  2190. NSLog(@"othersChatMessageAlert---2:%@",mutablemsg);
  2191. if (msgDict) {
  2192. ChatMessageModel *message = [ChatMessageModel modelWithDictionary:mutablemsg];
  2193. if ([message.chatId isEqualToString:self.chatId] || message.isSender ) {
  2194. return;
  2195. }
  2196. if ([message.chatId isEqualToString:self.userId] && message.type == 0) {
  2197. return;
  2198. }
  2199. if (message.nickName.length==0) {
  2200. return;
  2201. }
  2202. if (message.content.length==0) {
  2203. if (message.messageType==7) {
  2204. message.content=NSLocalizedString(@"ChatVtr-guaduan", @"");
  2205. }
  2206. else{
  2207. return;
  2208. }
  2209. }
  2210. NSLog(@"othersChatMessageAlert---3:%@",message.avatar);
  2211. // weakSelf(self);
  2212. [TopPopupView showWithNickname:message.nickName avatar:message.avatar message:message.content chatId:message.chatId type:message.type clickBlock:^{
  2213. // weakself.chatId = message.chatId;
  2214. // weakself.type = message.type;
  2215. // weakself.titlename = message.nickName;
  2216. // weakself.avatar = message.avatar;
  2217. // [weakself reloadAllData];
  2218. }];
  2219. }
  2220. }
  2221. }
  2222. -(NSString *)getLocalTime{
  2223. if(self.messageArray.count>0){
  2224. ChatMessageModel *lastObj = self.messageArray.lastObject;
  2225. NSDate *now = [NSDate date];
  2226. NSTimeInterval trt = [now timeIntervalSince1970];
  2227. NSInteger time = trt*1000;
  2228. if(time<lastObj.timestamp){
  2229. time =lastObj.timestamp+1;
  2230. }
  2231. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  2232. return strtime;
  2233. }
  2234. else{
  2235. NSDate *now = [NSDate date];
  2236. NSTimeInterval trt = [now timeIntervalSince1970];
  2237. NSInteger time = trt*1000;
  2238. NSString *strtime = [NSString stringWithFormat:@"%ld",(long)time];
  2239. return strtime;
  2240. }
  2241. }
  2242. @end