今天遇到一個(gè)情況肖油,首次安裝應(yīng)用程序统舀,在APP中長按進(jìn)行語音輸入時(shí),檢測iPhone麥克風(fēng)權(quán)限時(shí)澄港,系統(tǒng)會(huì)彈出“XXX想想訪問您的麥克風(fēng)”提示框椒涯。點(diǎn)擊 好/不允許 之后,發(fā)現(xiàn)頁面停留在長按的狀態(tài)下回梧。废岂。。就仿佛按鈕長按的手勢被打斷一樣
然后開始研究為什么會(huì)出現(xiàn)這種情況狱意。湖苞。。
- (void)didLongPress:(UILongPressGestureRecognizer *)gestureRecognizer {
if (gestureRecognizer.state == UIGestureRecognizerStateBegan) {
//按下按鈕详囤,開始語音識別
if (self.voiceRecogStart) {
self.voiceRecogStart(); //對應(yīng)更改顯示文字
}
}else if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
//松開按鈕财骨,語音識別結(jié)束
if (self.voiceRecogEnd) {
self.voiceRecogEnd();
}
self.speechLabel.text = @"長按進(jìn)行語音輸入";
}
}
voicePopView.voiceRecogStart = ^{
AVAudioSession *avSession = [AVAudioSession sharedInstance];
if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
[avSession requestRecordPermission:^(BOOL available) {
if (available) {
[weakSelf startSpeech];
}else {
weakSelf.searchtype = CSSearchingTextSearch;
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"麥克風(fēng)不可用,請?jiān)谙到y(tǒng)“設(shè)置”的權(quán)限管理中,允許“XXXX”訪問麥克風(fēng)" delegate:weakSelf cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alertView show];
});
}
}];
}
打斷點(diǎn)調(diào)試后隆箩,發(fā)現(xiàn)在上述問題重現(xiàn)過程中该贾,長按開始及結(jié)束兩種狀態(tài)都有進(jìn)入。再打斷點(diǎn)到長按開始響應(yīng)事件中捌臊,就發(fā)現(xiàn)問題了杨蛋。。長按狀態(tài)先是Began-Ended-Ended娃属,但在Ended之后六荒,才接著走Began里的響應(yīng)事件;つ贰矾端!
然后具體看代碼,發(fā)現(xiàn)是檢測用戶麥克風(fēng)授權(quán)的問題:
在檢測用戶麥克風(fēng)權(quán)限時(shí)卵皂,第一次詢問用戶要進(jìn)行特殊處理區(qū)分
AVAuthorizationStatus videoAuthStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
//判斷是否詢問過用戶授權(quán)麥克風(fēng)(否則檢測麥克風(fēng)權(quán)限秩铆,會(huì)被APP詢問授權(quán)彈窗打斷)
if (videoAuthStatus == AVAuthorizationStatusNotDetermined) {
// 未詢問過用戶是否授權(quán),進(jìn)行第一次詢問
//這里是關(guān)鍵 5票洹E孤辍!
AVAudioSession *avSession = [AVAudioSession sharedInstance];
if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
[avSession requestRecordPermission:^(BOOL available) {
}];
}
}else {
AVAudioSession *avSession = [AVAudioSession sharedInstance];
if ([avSession respondsToSelector:@selector(requestRecordPermission:)]) {
[avSession requestRecordPermission:^(BOOL available) {
if (available) {
[weakSelf startSpeech];
}else {
weakSelf.searchtype = CSSearchingTextSearch;
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"麥克風(fēng)不可用添祸,請?jiān)谙到y(tǒng)“設(shè)置”的權(quán)限管理中滚粟,允許“南方航空”訪問麥克風(fēng)" delegate:weakSelf cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alertView show];
});
}
}];
}
}
綜上,問題關(guān)鍵在于首次詢問用戶麥克風(fēng)授權(quán)刃泌,要區(qū)別對待凡壤。
等之后有時(shí)間,把iOS音頻相關(guān)內(nèi)容仔細(xì)學(xué)習(xí)一下.....