ChatController.m 96 KB

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