WFCUChatInputBar.m 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  1. //
  2. // ChatInputBar.m
  3. // WFChat UIKit
  4. //
  5. // Created by WF Chat on 2017/10/28.
  6. // Copyright © 2017年 WildFireChat. All rights reserved.
  7. //
  8. #import <AVFoundation/AVFoundation.h>
  9. #import <CoreText/CoreText.h>
  10. #import "WFCUChatInputBar.h"
  11. #import "WFCUFaceBoard.h"
  12. #import "WFCUVoiceRecordView.h"
  13. #import "WFCUPluginBoardView.h"
  14. #import "WFCUUtilities.h"
  15. #import "WFCULocationViewController.h"
  16. #import "WFCULocationPoint.h"
  17. #import "WFCUSelectFileViewController.h"
  18. #import "KZVideoViewController.h"
  19. #import "UIView+Toast.h"
  20. #import <WFChatClient/WFCChatClient.h>
  21. #import "WFCUMentionUserTableViewController.h"
  22. #define CHAT_INPUT_BAR_PADDING 8
  23. #define CHAT_INPUT_BAR_ICON_SIZE (CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_PADDING - CHAT_INPUT_BAR_PADDING)
  24. @implementation WFCUMetionInfo
  25. - (instancetype)initWithType:(int)type target:(NSString *)target range:(NSRange)range {
  26. self = [super init];
  27. if (self) {
  28. self.mentionType = type;
  29. self.target = target;
  30. self.range = range;
  31. }
  32. return self;
  33. }
  34. @end
  35. //@implementation TextInfo
  36. //
  37. //@end
  38. @interface WFCUChatInputBar () <UITextViewDelegate, WFCUFaceBoardDelegate, UIImagePickerControllerDelegate, AVAudioRecorderDelegate, AVAudioPlayerDelegate, WFCUPluginBoardViewDelegate, UIImagePickerControllerDelegate, LocationViewControllerDelegate, UIActionSheetDelegate, KZVideoViewControllerDelegate, WFCUMentionUserDelegate>
  39. @property (nonatomic, assign)BOOL textInput;
  40. @property (nonatomic, assign)BOOL voiceInput;
  41. @property (nonatomic, assign)BOOL emojInput;
  42. @property (nonatomic, assign)BOOL pluginInput;
  43. @property (nonatomic, strong)UIButton *voiceSwitchBtn;
  44. @property (nonatomic, strong)UIButton *emojSwitchBtn;
  45. @property (nonatomic, strong)UIButton *pluginSwitchBtn;
  46. @property (nonatomic, strong)UITextView *textInputView;
  47. @property (nonatomic, strong)UIButton *voiceInputBtn;
  48. @property (nonatomic, strong)UIView *emojInputView;
  49. @property (nonatomic, strong)UIView *pluginInputView;
  50. @property(nonatomic, weak)id<WFCUChatInputBarDelegate> delegate;
  51. @property (nonatomic, strong)WFCUVoiceRecordView *recordView;
  52. @property(nonatomic) AVAudioRecorder *recorder;
  53. @property(nonatomic) NSTimer *recordingTimer;
  54. @property(nonatomic) NSTimer *updateMeterTimer;
  55. @property(nonatomic, assign) int seconds;
  56. @property(nonatomic) BOOL recordCanceled;
  57. @property(nonatomic, weak)UIView *parentView;
  58. @property (nonatomic, strong)NSMutableArray<WFCUMetionInfo *> *mentionInfos;
  59. @property (nonatomic, strong)WFCCConversation *conversation;
  60. @property (nonatomic, assign)double lastTypingTime;
  61. @end
  62. @implementation WFCUChatInputBar
  63. - (instancetype)initWithParentView:(UIView *)parentView conversation:(WFCCConversation *)conversation delegate:(id<WFCUChatInputBarDelegate>)delegate {
  64. self = [super initWithFrame:CGRectMake(0, parentView.bounds.size.height - CHAT_INPUT_BAR_HEIGHT, parentView.bounds.size.width, CHAT_INPUT_BAR_HEIGHT)];
  65. if (self) {
  66. [parentView addSubview:self];
  67. [self initSubViews];
  68. self.delegate = delegate;
  69. self.parentView = parentView;
  70. self.mentionInfos = [[NSMutableArray alloc] init];
  71. self.conversation = conversation;
  72. self.lastTypingTime = 0;
  73. }
  74. return self;
  75. }
  76. - (void)initSubViews {
  77. [[NSNotificationCenter defaultCenter] addObserver:self
  78. selector:@selector(keyboardWillShow:)
  79. name:UIKeyboardWillShowNotification
  80. object:nil];
  81. [[NSNotificationCenter defaultCenter] addObserver:self
  82. selector:@selector(keyboardWillHide:)
  83. name:UIKeyboardWillHideNotification
  84. object:nil];
  85. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide:) name:UIKeyboardDidHideNotification object:nil];
  86. CGRect parentRect = self.bounds;
  87. self.voiceSwitchBtn = [[UIButton alloc] initWithFrame:CGRectMake(CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_ICON_SIZE, CHAT_INPUT_BAR_ICON_SIZE)];
  88. [self.voiceSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_voice"] forState:UIControlStateNormal];
  89. [self.voiceSwitchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  90. [self.voiceSwitchBtn addTarget:self action:@selector(onSwitchBtn:) forControlEvents:UIControlEventTouchDown];
  91. [self addSubview:self.voiceSwitchBtn];
  92. self.pluginSwitchBtn = [[UIButton alloc] initWithFrame:CGRectMake(parentRect.size.width - CHAT_INPUT_BAR_HEIGHT + CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_ICON_SIZE, CHAT_INPUT_BAR_ICON_SIZE)];
  93. [self.pluginSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_plugin"] forState:UIControlStateNormal];
  94. [self.pluginSwitchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  95. [self.pluginSwitchBtn addTarget:self action:@selector(onSwitchBtn:) forControlEvents:UIControlEventTouchDown];
  96. [self addSubview:self.pluginSwitchBtn];
  97. self.emojSwitchBtn = [[UIButton alloc] initWithFrame:CGRectMake(parentRect.size.width - CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_ICON_SIZE, CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_ICON_SIZE, CHAT_INPUT_BAR_ICON_SIZE)];
  98. [self.emojSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_emoj"] forState:UIControlStateNormal];
  99. [self.emojSwitchBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  100. [self.emojSwitchBtn addTarget:self action:@selector(onSwitchBtn:) forControlEvents:UIControlEventTouchDown];
  101. [self addSubview:self.emojSwitchBtn];
  102. self.textInputView = [[UITextView alloc] initWithFrame:CGRectMake(CHAT_INPUT_BAR_HEIGHT, CHAT_INPUT_BAR_PADDING, parentRect.size.width - CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_HEIGHT + CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_ICON_SIZE)];
  103. self.textInputView.delegate = self;
  104. self.textInputView.layoutManager.allowsNonContiguousLayout = NO;
  105. [self.textInputView setExclusiveTouch:YES];
  106. [self.textInputView setTextColor:[UIColor blackColor]];
  107. [self.textInputView setFont:[UIFont systemFontOfSize:16]];
  108. [self.textInputView setReturnKeyType:UIReturnKeySend];
  109. self.textInputView.backgroundColor = [UIColor whiteColor];
  110. self.textInputView.enablesReturnKeyAutomatically = YES;
  111. self.textInputView.layer.cornerRadius = 4;
  112. self.textInputView.layer.masksToBounds = YES;
  113. self.textInputView.layer.borderWidth = 0.5f;
  114. self.textInputView.layer.borderColor = HEXCOLOR(0xdbdbdd).CGColor;
  115. [self addSubview:self.textInputView];
  116. self.voiceInputBtn = [[UIButton alloc] initWithFrame:CGRectMake(CHAT_INPUT_BAR_HEIGHT, CHAT_INPUT_BAR_PADDING, parentRect.size.width - CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_HEIGHT - CHAT_INPUT_BAR_HEIGHT + CHAT_INPUT_BAR_PADDING, CHAT_INPUT_BAR_ICON_SIZE)];
  117. [self.voiceInputBtn setTitle:@"按下 说话" forState:UIControlStateNormal];
  118. [self.voiceInputBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  119. self.voiceInputBtn.layer.cornerRadius = 4;
  120. self.voiceInputBtn.layer.masksToBounds = YES;
  121. self.voiceInputBtn.layer.borderWidth = 0.5f;
  122. self.voiceInputBtn.layer.borderColor = HEXCOLOR(0xdbdbdd).CGColor;
  123. [self addSubview:self.voiceInputBtn];
  124. self.layer.borderWidth = 0.5f;
  125. self.layer.borderColor = HEXCOLOR(0xdbdbdd).CGColor;
  126. self.inputBarStatus = ChatInputBarDefaultStatus;
  127. [self.voiceInputBtn addTarget:self action:@selector(onTouchDown:) forControlEvents:UIControlEventTouchDown];
  128. [self.voiceInputBtn addTarget:self action:@selector(onTouchDragExit:) forControlEvents:UIControlEventTouchDragExit];
  129. [self.voiceInputBtn addTarget:self action:@selector(onTouchDragEnter:) forControlEvents:UIControlEventTouchDragEnter];
  130. [self.voiceInputBtn addTarget:self action:@selector(onTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
  131. [self.voiceInputBtn addTarget:self action:@selector(onTouchUpOutside:) forControlEvents:UIControlEventTouchUpOutside];
  132. [self.voiceInputBtn addTarget:self action:@selector(onTouchUpOutside:) forControlEvents:UIControlEventTouchCancel];
  133. self.voiceInputBtn.hidden = YES;
  134. self.textInputView.returnKeyType = UIReturnKeySend;
  135. self.textInputView.delegate = self;
  136. }
  137. - (void)onTouchDown:(id)sender {
  138. if ([self canRecord]) {
  139. _recordView = [[WFCUVoiceRecordView alloc] initWithFrame:CGRectMake(self.parentView.bounds.size.width/2 - 70, self.parentView.bounds.size.height/2 - 70, 140, 140)];
  140. _recordView.center = self.parentView.center;
  141. [self.parentView addSubview:_recordView];
  142. [self.parentView bringSubviewToFront:_recordView];
  143. [self recordStart];
  144. }
  145. }
  146. - (void)recordStart {
  147. if (self.recorder.recording) {
  148. return;
  149. }
  150. //[self stopPlayer];
  151. [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
  152. if (granted) {
  153. AVAudioSession *session = [AVAudioSession sharedInstance];
  154. [session setCategory:AVAudioSessionCategoryRecord error:nil];
  155. BOOL r = [session setActive:YES error:nil];
  156. if (!r) {
  157. NSLog(@"activate audio session fail");
  158. return;
  159. }
  160. NSLog(@"start record...");
  161. NSArray *pathComponents = [NSArray arrayWithObjects:
  162. [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject],
  163. @"voice.wav",
  164. nil];
  165. NSURL *outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
  166. // Define the recorder setting
  167. NSMutableDictionary *recordSetting = [[NSMutableDictionary alloc] init];
  168. [recordSetting setValue:[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
  169. [recordSetting setValue:[NSNumber numberWithFloat:8000] forKey:AVSampleRateKey];
  170. [recordSetting setValue:[NSNumber numberWithInt:2] forKey:AVNumberOfChannelsKey];
  171. self.recorder = [[AVAudioRecorder alloc] initWithURL:outputFileURL settings:recordSetting error:NULL];
  172. self.recorder.delegate = self;
  173. self.recorder.meteringEnabled = YES;
  174. if (![self.recorder prepareToRecord]) {
  175. NSLog(@"prepare record fail");
  176. return;
  177. }
  178. if (![self.recorder record]) {
  179. NSLog(@"start record fail");
  180. return;
  181. }
  182. self.recordCanceled = NO;
  183. self.seconds = 0;
  184. self.recordingTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFired:) userInfo:nil repeats:YES];
  185. self.updateMeterTimer = [NSTimer scheduledTimerWithTimeInterval:0.05
  186. target:self
  187. selector:@selector(updateMeter:)
  188. userInfo:nil
  189. repeats:YES];
  190. } else {
  191. [[[UIAlertView alloc] initWithTitle:@"警告" message:@"无法录音,请到设置-隐私-麦克风,允许程序访问" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
  192. }
  193. }];
  194. }
  195. - (void)recordCancel {
  196. NSLog(@"touch cancel");
  197. if (self.recorder.recording) {
  198. NSLog(@"cancel record...");
  199. self.recordCanceled = YES;
  200. [self stopRecord];
  201. }
  202. }
  203. - (void)onTouchDragExit:(id)sender {
  204. [self.recordView recordButtonDragOutside];
  205. }
  206. - (void)onTouchDragEnter:(id)sender {
  207. [self.recordView recordButtonDragInside];
  208. }
  209. - (void)onTouchUpInside:(id)sender {
  210. [self.recordView removeFromSuperview];
  211. [self recordEnd];
  212. }
  213. - (void)onTouchUpOutside:(id)sender {
  214. [self.recordView removeFromSuperview];
  215. [self recordCancel];
  216. }
  217. - (BOOL)canRecord {
  218. __block BOOL bCanRecord = YES;
  219. if ([[AVAudioSession sharedInstance]
  220. respondsToSelector:@selector(requestRecordPermission:)]) {
  221. [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
  222. bCanRecord = granted;
  223. dispatch_async(dispatch_get_main_queue(), ^{
  224. bCanRecord = granted;
  225. if (granted) {
  226. bCanRecord = YES;
  227. } else {
  228. }
  229. });
  230. }];
  231. }
  232. return bCanRecord;
  233. }
  234. - (void)timerFired:(NSTimer*)timer {
  235. self.seconds = self.seconds + 1;
  236. int minute = self.seconds/60;
  237. int s = self.seconds%60;
  238. NSString *str = [NSString stringWithFormat:@"%02d:%02d", minute, s];
  239. NSLog(@"timer:%@", str);
  240. int countdown = 60 - self.seconds;
  241. if (countdown <= 10) {
  242. [self.recordView setCountdown:countdown];
  243. }
  244. if (countdown <= 0) {
  245. [self.recordView removeFromSuperview];
  246. [self recordEnd];
  247. } else {
  248. [self notifyTyping:1];
  249. }
  250. }
  251. - (void)updateMeter:(NSTimer*)timer {
  252. double voiceMeter = 0;
  253. if ([self.recorder isRecording]) {
  254. [self.recorder updateMeters];
  255. //获取音量的平均值 [recorder averagePowerForChannel:0];
  256. //音量的最大值 [recorder peakPowerForChannel:0];
  257. double lowPassResults = pow(10, (0.05 * [self.recorder peakPowerForChannel:0]));
  258. voiceMeter = lowPassResults;
  259. }
  260. [self.recordView setVoiceImage:voiceMeter];
  261. }
  262. -(void)recordEnd {
  263. if (self.recorder.recording) {
  264. NSLog(@"stop record...");
  265. self.recordCanceled = NO;
  266. [self stopRecord];
  267. }
  268. }
  269. -(void)stopRecord {
  270. [self.recorder stop];
  271. [self.recordingTimer invalidate];
  272. self.recordingTimer = nil;
  273. [self.updateMeterTimer invalidate];
  274. self.updateMeterTimer = nil;
  275. AVAudioSession *audioSession = [AVAudioSession sharedInstance];
  276. BOOL r = [audioSession setActive:NO error:nil];
  277. if (!r) {
  278. NSLog(@"deactivate audio session fail");
  279. }
  280. }
  281. - (void)resetInputBarStatue {
  282. if (self.inputBarStatus != ChatInputBarRecordStatus) {
  283. self.inputBarStatus = ChatInputBarDefaultStatus;
  284. }
  285. }
  286. - (void)onSwitchBtn:(id)sender {
  287. if (sender == self.voiceSwitchBtn) {
  288. if (self.voiceInput && self.inputBarStatus != ChatInputBarDefaultStatus) {
  289. self.inputBarStatus = ChatInputBarKeyboardStatus;
  290. } else {
  291. self.inputBarStatus = ChatInputBarRecordStatus;
  292. }
  293. } else if(sender == self.emojSwitchBtn) {
  294. if (self.emojInput && self.inputBarStatus != ChatInputBarDefaultStatus) {
  295. self.inputBarStatus = ChatInputBarKeyboardStatus;
  296. } else {
  297. self.inputBarStatus = ChatInputBarEmojiStatus;
  298. }
  299. } else if (sender == self.pluginSwitchBtn) {
  300. if (self.pluginInput && self.inputBarStatus != ChatInputBarDefaultStatus) {
  301. self.inputBarStatus = ChatInputBarKeyboardStatus;
  302. } else {
  303. self.inputBarStatus = ChatInputBarPluginStatus;
  304. }
  305. }
  306. }
  307. - (void)setInputBarStatus:(ChatInputBarStatus)inputBarStatus {
  308. _inputBarStatus = inputBarStatus;
  309. switch (inputBarStatus) {
  310. case ChatInputBarKeyboardStatus:
  311. self.voiceInput = NO;
  312. self.emojInput = NO;
  313. self.pluginInput = NO;
  314. self.textInput = YES;
  315. break;
  316. case ChatInputBarPluginStatus:
  317. self.voiceInput = NO;
  318. self.emojInput = NO;
  319. self.pluginInput = YES;
  320. self.textInput = NO;
  321. break;
  322. case ChatInputBarEmojiStatus:
  323. self.voiceInput = NO;
  324. self.emojInput = YES;
  325. self.pluginInput = NO;
  326. self.textInput = NO;
  327. break;
  328. case ChatInputBarRecordStatus:
  329. self.voiceInput = YES;
  330. self.emojInput = NO;
  331. self.pluginInput = NO;
  332. self.textInput = NO;
  333. break;
  334. case ChatInputBarPublicStatus:
  335. self.voiceInput = NO;
  336. self.emojInput = NO;
  337. self.pluginInput = NO;
  338. self.textInput = NO;
  339. break;
  340. case ChatInputBarDefaultStatus:
  341. self.voiceInput = NO;
  342. self.emojInput = NO;
  343. self.pluginInput = NO;
  344. self.textInput = YES;
  345. [self.textInputView resignFirstResponder];
  346. break;
  347. default:
  348. break;
  349. }
  350. }
  351. - (void)setVoiceInput:(BOOL)voiceInput {
  352. _voiceInput = voiceInput;
  353. if (voiceInput) {
  354. [self.textInputView setHidden:YES];
  355. [self.voiceInputBtn setHidden:NO];
  356. if (self.textInputView.isFirstResponder) {
  357. [self.textInputView resignFirstResponder];
  358. }
  359. [self.voiceSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_keyboard"] forState:UIControlStateNormal];
  360. } else {
  361. [self.textInputView setHidden:NO];
  362. [self.voiceInputBtn setHidden:YES];
  363. [self.voiceSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_voice"] forState:UIControlStateNormal];
  364. }
  365. }
  366. - (void)setEmojInput:(BOOL)emojInput {
  367. _emojInput = emojInput;
  368. if (emojInput) {
  369. [self.textInputView setHidden:NO];
  370. [self.voiceInputBtn setHidden:YES];
  371. self.textInputView.inputView = self.emojInputView;
  372. if (!self.textInputView.isFirstResponder) {
  373. [self.textInputView becomeFirstResponder];
  374. }
  375. [self.textInputView reloadInputViews];
  376. [self.emojSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_keyboard"] forState:UIControlStateNormal];
  377. } else {
  378. [self.emojSwitchBtn setImage:[UIImage imageNamed:@"chat_input_bar_emoj"] forState:UIControlStateNormal];
  379. }
  380. }
  381. - (void)setPluginInput:(BOOL)pluginInput {
  382. _pluginInput = pluginInput;
  383. if (pluginInput) {
  384. [self.textInputView setHidden:NO];
  385. [self.voiceInputBtn setHidden:YES];
  386. self.textInputView.inputView = self.pluginInputView;
  387. if (!self.textInputView.isFirstResponder) {
  388. [self.textInputView becomeFirstResponder];
  389. }
  390. [self.textInputView reloadInputViews];
  391. }
  392. }
  393. - (void)setTextInput:(BOOL)textInput {
  394. _textInput = textInput;
  395. if (textInput) {
  396. [self.textInputView setHidden:NO];
  397. [self.voiceInputBtn setHidden:YES];
  398. self.textInputView.inputView = nil;
  399. if (!self.textInputView.isFirstResponder && _inputBarStatus == ChatInputBarKeyboardStatus) {
  400. [self.textInputView becomeFirstResponder];
  401. }
  402. if (_inputBarStatus == ChatInputBarKeyboardStatus) {
  403. [self.textInputView reloadInputViews];
  404. }
  405. }
  406. }
  407. - (void)notifyTyping:(WFCCTypingType)type {
  408. double now = [[NSDate date] timeIntervalSince1970];
  409. if (self.lastTypingTime + TYPING_INTERVAL < now) {
  410. if ([self.delegate respondsToSelector:@selector(onTyping:)]) {
  411. [self.delegate onTyping:type];
  412. }
  413. self.lastTypingTime = now;
  414. }
  415. }
  416. - (void)setDraft:(NSString *)draft {
  417. NSError *__error = nil;
  418. NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:[draft dataUsingEncoding:NSUTF8StringEncoding]
  419. options:kNilOptions
  420. error:&__error];
  421. BOOL hasMentionInfo = NO;
  422. NSString *text = nil;
  423. NSMutableArray<WFCUMetionInfo *> *mentionInfos = [[NSMutableArray alloc] init];
  424. if (!__error) {
  425. if (dictionary[@"text"] != nil && [dictionary[@"mentions"] isKindOfClass:[NSArray class]]) {
  426. hasMentionInfo = YES;
  427. text = dictionary[@"text"];
  428. NSArray *mentions = dictionary[@"mentions"];
  429. [mentions enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  430. NSDictionary *dic = (NSDictionary *)obj;
  431. WFCUMetionInfo *mentionInfo = [[WFCUMetionInfo alloc] init];
  432. mentionInfo.target = dic[@"target"];
  433. mentionInfo.mentionType = [dic[@"type"] intValue];
  434. mentionInfo.range = NSMakeRange([dic[@"loc"] integerValue], [dic[@"len"] integerValue]);
  435. [mentionInfos addObject:mentionInfo];
  436. }];
  437. }
  438. }
  439. if (hasMentionInfo) {
  440. draft = text;
  441. }
  442. [self textView:self.textInputView shouldChangeTextInRange:NSMakeRange(0, 0) replacementText:draft];
  443. self.textInputView.text = draft;
  444. self.mentionInfos = mentionInfos;
  445. }
  446. - (NSString *)draft {
  447. if (self.mentionInfos.count) {
  448. NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
  449. [dataDict setObject:self.textInputView.text forKey:@"text"];
  450. NSMutableArray *mentions = [[NSMutableArray alloc] init];
  451. [self.mentionInfos enumerateObjectsUsingBlock:^(WFCUMetionInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  452. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
  453. [dic setObject:obj.target forKey:@"target"];
  454. [dic setObject:@(obj.mentionType) forKey:@"type"];
  455. [dic setObject:@(obj.range.location) forKey:@"loc"];
  456. [dic setObject:@(obj.range.length) forKey:@"len"];
  457. [mentions addObject:dic];
  458. }];
  459. [dataDict setObject:mentions forKey:@"mentions"];
  460. NSData *data = [NSJSONSerialization dataWithJSONObject:dataDict
  461. options:kNilOptions
  462. error:nil];
  463. return [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  464. } else {
  465. return self.textInputView.text;
  466. }
  467. }
  468. - (UIView *)emojInputView {
  469. if (!_emojInputView) {
  470. _emojInputView = [[WFCUFaceBoard alloc] init];
  471. ((WFCUFaceBoard*)_emojInputView).delegate = self;
  472. }
  473. return _emojInputView;
  474. }
  475. - (UIView *)pluginInputView {
  476. if (!_pluginInputView) {
  477. _pluginInputView = [[WFCUPluginBoardView alloc] initWithDelegate:self withVoip:(self.conversation.type == Single_Type || self.conversation.type == Group_Type)];
  478. }
  479. return _pluginInputView;
  480. }
  481. - (void)keyboardWillShow:(NSNotification *)notification {
  482. if (![self.textInputView isFirstResponder]) {
  483. return;
  484. }
  485. NSDictionary *userInfo = [notification userInfo];
  486. NSValue *value = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
  487. CGRect keyboardRect = [value CGRectValue];
  488. int height = keyboardRect.size.height - kTabbarSafeBottomMargin;
  489. CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  490. CGRect frame = CGRectMake(0, self.superview.bounds.size.height - self.bounds.size.height - height, self.superview.bounds.size.width, self.bounds.size.height);
  491. [self.delegate willChangeFrame:frame withDuration:duration keyboardShowing:YES];
  492. [UIView animateWithDuration:duration animations:^{
  493. self.frame = frame;
  494. }];
  495. }
  496. - (void)keyboardWillHide:(NSNotification *)notification {
  497. NSDictionary *userInfo = [notification userInfo];
  498. CGFloat duration = [[userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
  499. CGRect frame = CGRectMake(0, self.superview.bounds.size.height - self.bounds.size.height, self.superview.bounds.size.width, self.bounds.size.height);
  500. [self.delegate willChangeFrame:frame withDuration:duration keyboardShowing:NO];
  501. [UIView animateWithDuration:duration animations:^{
  502. self.frame = frame;
  503. }];
  504. }
  505. -(void)keyboardDidHide:(NSNotification *)notification{
  506. if ((self.emojInput || self.pluginInput || self.textInput) && self.inputBarStatus != ChatInputBarDefaultStatus) {
  507. [self.textInputView becomeFirstResponder];
  508. }
  509. }
  510. - (BOOL)appendMention:(NSString *)userId name:(NSString *)userName {
  511. if (self.conversation.type == Group_Type) {
  512. NSString *mentionText = [NSString stringWithFormat:@"@%@ ", userName];
  513. [self didMentionType:1 user:userId range:NSMakeRange(self.textInputView.selectedRange.location, mentionText.length) text:mentionText];
  514. return YES;
  515. } else {
  516. return NO;
  517. }
  518. }
  519. - (void)paste:(id)sender {
  520. [self.textInputView paste:sender];
  521. }
  522. #pragma mark - AVAudioRecorderDelegate
  523. - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {
  524. NSLog(@"record finish:%d", flag);
  525. if (!flag) {
  526. return;
  527. }
  528. if (self.recordCanceled) {
  529. return;
  530. }
  531. if (self.seconds < 1) {
  532. NSLog(@"record time too short");
  533. [[[UIAlertView alloc] initWithTitle:@"警告" message:@"录音时间太短了" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil] show];
  534. return;
  535. }
  536. [self.delegate recordDidEnd:[recorder.url path] duration:self.seconds error:nil];
  537. [[NSFileManager defaultManager] removeItemAtURL:recorder.url error:nil];
  538. }
  539. #pragma mark - FaceBoardDelegate
  540. - (void)didTouchEmoj:(NSString *)emojString {
  541. NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:emojString];
  542. UIFont *font = [UIFont fontWithName:@"Heiti SC-Bold" size:16];
  543. [attStr addAttribute:(__bridge NSString*)kCTFontAttributeName value:(id)CFBridgingRelease(CTFontCreateWithName((CFStringRef)font.fontName,
  544. 16,
  545. NULL)) range:NSMakeRange(0, emojString.length)];
  546. NSInteger cursorPosition;
  547. if (self.textInputView.selectedTextRange) {
  548. cursorPosition = self.textInputView.selectedRange.location ;
  549. } else {
  550. cursorPosition = 0;
  551. }
  552. //获取光标位置
  553. if(cursorPosition> self.textInputView.textStorage.length)
  554. cursorPosition = self.textInputView.textStorage.length;
  555. [self.textInputView.textStorage
  556. insertAttributedString:attStr atIndex:cursorPosition];
  557. NSRange range;
  558. range.location = self.textInputView.selectedRange.location + emojString.length;
  559. range.length = 1;
  560. self.textInputView.selectedRange = range;
  561. }
  562. - (void)didTouchBackEmoj {
  563. [self.textInputView deleteBackward];
  564. }
  565. - (void)didTouchSendEmoj {
  566. [self sendAndCleanTextView];
  567. }
  568. - (void)sendAndCleanTextView {
  569. [self.delegate didTouchSend:self.textInputView.text withMentionInfos:self.mentionInfos];
  570. self.textInputView.text = nil;
  571. [self.mentionInfos removeAllObjects];
  572. [self changeTextViewHeight:32 needUpdateText:NO updateRange:NSMakeRange(0, 0)];
  573. }
  574. - (void)didSelectedSticker:(NSString *)stickerPath {
  575. if ([self.delegate respondsToSelector:@selector(didSelectSticker:)]) {
  576. [self.delegate didSelectSticker:stickerPath];
  577. }
  578. }
  579. #pragma mark - UITextViewDelegate
  580. - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
  581. if ([text isEqualToString:@"\n"]){ //判断输入的字是否是回车,即按下return
  582. [self sendAndCleanTextView];
  583. return NO;
  584. }
  585. BOOL needUpdateText = NO;
  586. if(self.conversation.type == Group_Type) {
  587. if ([text isEqualToString:@"@"]) {
  588. WFCUMentionUserTableViewController *mvc = [[WFCUMentionUserTableViewController alloc] init];
  589. mvc.groupId = self.conversation.target;
  590. mvc.delegate = self;
  591. mvc.range = range;
  592. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:mvc];
  593. [[self.delegate requireNavi] presentViewController:nav animated:YES completion:nil];
  594. return NO;
  595. }
  596. if (text.length == 0) {
  597. WFCUMetionInfo *deletedMention;
  598. for (WFCUMetionInfo *mentionInfo in self.mentionInfos) {
  599. if ((mentionInfo.range.location >= range.location && mentionInfo.range.location < range.location + range.length) ||
  600. (range.location >= mentionInfo.range.location && range.location < mentionInfo.range.location + mentionInfo.range.length)) {
  601. deletedMention = mentionInfo;
  602. }
  603. }
  604. if (deletedMention) {
  605. range = deletedMention.range;
  606. [self.mentionInfos removeObject:deletedMention];
  607. needUpdateText = YES;
  608. }
  609. } else {
  610. for (WFCUMetionInfo *mentionInfo in self.mentionInfos) {
  611. if (range.location <= mentionInfo.range.location) {
  612. mentionInfo.range = NSMakeRange(mentionInfo.range.location - range.length + text.length, mentionInfo.range.length);
  613. }
  614. }
  615. }
  616. }
  617. NSString *oldStr = textView.text;
  618. NSString *newStr = [oldStr stringByReplacingCharactersInRange:range withString:text];
  619. CGFloat textAreaWidth = textView.frame.size.width - 2 * textView.textContainer.lineFragmentPadding;
  620. CGSize size = [WFCUUtilities getTextDrawingSize:newStr font:[UIFont systemFontOfSize:16] constrainedSize:CGSizeMake(textAreaWidth, 1000)];
  621. [self changeTextViewHeight:size.height needUpdateText:needUpdateText updateRange:range];
  622. return YES;
  623. }
  624. - (void)changeTextViewHeight:(CGFloat)height needUpdateText:(BOOL)needUpdateText updateRange:(NSRange)range {
  625. CGRect tvFrame = self.textInputView.frame;
  626. CGRect baseFrame = self.frame;
  627. CGRect voiceFrame = self.voiceSwitchBtn.frame;
  628. CGRect emojFrame = self.emojSwitchBtn.frame;
  629. CGRect extendFrame = self.pluginSwitchBtn.frame;
  630. CGFloat diff = 0;
  631. if (height <= 32.f) {
  632. tvFrame.size.height = 32.f;
  633. diff = (48.f - baseFrame.size.height);
  634. baseFrame.size.height = 48.f;
  635. } else if (height > 32.f && height < 50.f) {
  636. tvFrame.size.height = 50.f;
  637. diff = (66.f - baseFrame.size.height);
  638. baseFrame.size.height = 66.f;
  639. } else {
  640. tvFrame.size.height = 65.f;
  641. diff = (81.f - baseFrame.size.height);
  642. baseFrame.size.height = 81.f;
  643. }
  644. baseFrame.origin.y -= diff;
  645. voiceFrame.origin.y += diff;
  646. emojFrame.origin.y += diff;
  647. extendFrame.origin.y += diff;
  648. float duration = 0.5f;
  649. [self.delegate willChangeFrame:baseFrame withDuration:duration keyboardShowing:YES];
  650. __weak typeof(self)ws = self;
  651. [UIView animateWithDuration:duration animations:^{
  652. ws.textInputView.frame = tvFrame;
  653. self.frame = baseFrame;
  654. self.voiceSwitchBtn.frame = voiceFrame;
  655. self.emojSwitchBtn.frame = emojFrame;
  656. self.pluginSwitchBtn.frame = extendFrame;
  657. if(needUpdateText) {
  658. [ws.textInputView.textStorage replaceCharactersInRange:range withString:@" "];
  659. }
  660. }];
  661. }
  662. - (void)textViewDidChangeSelection:(UITextView *)textView {
  663. if (self.textInputView == textView && self.conversation.type == Group_Type) {
  664. NSRange range = textView.selectedRange;
  665. for (WFCUMetionInfo *mention in self.mentionInfos) {
  666. if (range.location > mention.range.location && range.location < mention.range.location + mention.range.length) {
  667. if (range.length == 0) {
  668. if(range.location == mention.range.location + mention.range.length - 1) {
  669. range.location = mention.range.location;
  670. } else {
  671. range = NSMakeRange(mention.range.location + mention.range.length, 0);
  672. }
  673. } else {
  674. long length = range.length - (mention.range.location + mention.range.length) + range.location;
  675. if (length < 0) {
  676. length = 0;
  677. }
  678. range = NSMakeRange(mention.range.location + mention.range.length, length);
  679. }
  680. textView.selectedRange = range;
  681. break;
  682. }
  683. }
  684. }
  685. }
  686. - (void)textViewDidChange:(UITextView *)textView {
  687. if (textView.text.length > 0) {
  688. [self notifyTyping:0];
  689. }
  690. }
  691. #pragma mark - PluginBoardViewDelegate
  692. - (void)onItemClicked:(NSUInteger)itemTag {
  693. UINavigationController *navi = [self.delegate requireNavi];
  694. self.inputBarStatus = ChatInputBarDefaultStatus;
  695. if (itemTag == 1) {
  696. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  697. picker.delegate = self;
  698. #if TARGET_IPHONE_SIMULATOR
  699. picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  700. #else
  701. if (itemTag == 1) {
  702. picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  703. } else if(itemTag == 2){
  704. picker.sourceType = UIImagePickerControllerSourceTypeCamera;
  705. }
  706. #endif
  707. [navi presentViewController:picker animated:YES completion:nil];
  708. [self checkAndAlertCameraAccessRight];
  709. } else if(itemTag == 2) {
  710. #if TARGET_IPHONE_SIMULATOR
  711. [self makeToast:@"模拟器不支持相机" duration:1 position:CSToastPositionCenter];
  712. UIImagePickerController *picker = [[UIImagePickerController alloc] init];
  713. picker.delegate = self;
  714. picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
  715. [navi presentViewController:picker animated:YES completion:nil];
  716. [self checkAndAlertCameraAccessRight];
  717. #else
  718. KZVideoViewController *videoVC = [[KZVideoViewController alloc] init];
  719. videoVC.delegate = self;
  720. [videoVC startAnimationWithType:KZVideoViewShowTypeSingle selectExist:NO];
  721. double now = [[NSDate date] timeIntervalSince1970];
  722. [self notifyTyping:2];
  723. #endif
  724. } else if(itemTag == 3){
  725. WFCULocationViewController *vc = [[WFCULocationViewController alloc] initWithDelegate:self];
  726. UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
  727. [navi presentViewController:nav animated:YES completion:nil];
  728. [self notifyTyping:3];
  729. return;
  730. } else if(itemTag == 4) {
  731. UIActionSheet *actionSheet =
  732. [[UIActionSheet alloc] initWithTitle:nil
  733. delegate:self
  734. cancelButtonTitle:@"取消"
  735. destructiveButtonTitle:@"视频"
  736. otherButtonTitles:@"音频", nil];
  737. [actionSheet showInView:self.parentView];
  738. } else if(itemTag == 5) {
  739. WFCUSelectFileViewController *sfvc = [[WFCUSelectFileViewController alloc] init];
  740. UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:sfvc];
  741. __weak typeof(self) ws = self;
  742. sfvc.selectResult = ^(NSArray *selectFiles) {
  743. [ws.delegate didSelectFiles:selectFiles];
  744. };
  745. [[self.delegate requireNavi] presentViewController:navi animated:YES completion:nil];
  746. [self notifyTyping:4];
  747. }
  748. }
  749. - (void)checkAndAlertCameraAccessRight {
  750. AVAuthorizationStatus authStatus =
  751. [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  752. if (authStatus == AVAuthorizationStatusDenied ||
  753. authStatus == AVAuthorizationStatusRestricted) {
  754. UIAlertView *alertView = [[UIAlertView alloc]
  755. initWithTitle:@"拍照权限"
  756. message:@"需要拍照权限,请在设置里打开"
  757. delegate:nil
  758. cancelButtonTitle:@"确认"
  759. otherButtonTitles:nil, nil];
  760. [alertView show];
  761. }
  762. }
  763. #pragma mark - UIImagePickerControllerDelegate<NSObject>
  764. - (void)imagePickerController:(UIImagePickerController *)picker
  765. didFinishPickingImage:(UIImage *)image
  766. editingInfo:(NSDictionary *)editingInfo {
  767. [picker dismissViewControllerAnimated:YES completion:nil];
  768. [self.delegate imageDidCapture:image];
  769. }
  770. - (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
  771. [picker dismissViewControllerAnimated:YES completion:nil];
  772. }
  773. #pragma mark - LocationViewControllerDelegate <NSObject>
  774. - (void)onSendLocation:(WFCULocationPoint *)locationPoint {
  775. [self.delegate locationDidSelect:locationPoint.coordinate locationName:locationPoint.title mapScreenShot:locationPoint.thumbnail];
  776. }
  777. #pragma mark - UIActionSheetDelegate
  778. - (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  779. if (buttonIndex == 0) {
  780. [self.delegate didTouchVideoBtn:NO];
  781. } else if(buttonIndex == 1) {
  782. [self.delegate didTouchVideoBtn:YES];
  783. }
  784. }
  785. #pragma mark - KZVideoViewControllerDelegate
  786. - (void)videoViewController:(KZVideoViewController *)videoController didCaptureImage:(UIImage *)image {
  787. [self.delegate imageDidCapture:image];
  788. }
  789. - (void)videoViewController:(KZVideoViewController *)videoController didRecordVideo:(KZVideoModel *)videoModel {
  790. [self.delegate videoDidCapture:videoModel.videoAbsolutePath thumbnail:[UIImage imageWithContentsOfFile:videoModel.thumAbsolutePath] duration:10];
  791. }
  792. - (void)videoViewControllerDidCancel:(KZVideoViewController *)videoController {
  793. }
  794. #pragma mark - WFCUMentionUserDelegate
  795. - (void)didMentionType:(int)type user:(NSString *)userId range:(NSRange)range text:(NSString *)text {
  796. [self textView:self.textInputView shouldChangeTextInRange:NSMakeRange(range.location, 0) replacementText:text];
  797. [self.mentionInfos addObject:[[WFCUMetionInfo alloc] initWithType:type target:userId range:NSMakeRange(range.location, range.length)]];
  798. NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc]initWithString:text];
  799. UIFont *font = [UIFont fontWithName:@"Heiti SC-Bold" size:16];
  800. [attStr addAttribute:(__bridge NSString*)kCTFontAttributeName value:(id)CFBridgingRelease(CTFontCreateWithName((CFStringRef)font.fontName,
  801. 16,
  802. NULL)) range:NSMakeRange(0, text.length)];
  803. [self.textInputView.textStorage
  804. insertAttributedString:attStr atIndex:range.location];
  805. self.textInputView.selectedRange = range;
  806. }
  807. - (void)didCancelMentionAtRange:(NSRange)range {
  808. [self.textInputView.textStorage replaceCharactersInRange:NSMakeRange(range.location, 0) withString:@"@"];
  809. self.textInputView.selectedRange = range;
  810. }
  811. @end