unity iOS检测是否插入耳机并给出提示

OC代码:

void ShowAlert()
{
    AVAudioSessionRouteDescription* route = [[AVAudioSession sharedInstance] currentRoute];
    for (AVAudioSessionPortDescription* desc in [route outputs])
    {
        if ([[desc portType] isEqualToString:AVAudioSessionPortHeadphones])
        {
            printf("插着耳机");
        }
        else
        {
            printf("没有插着耳机");
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"连接耳机"
										message:@"请连接耳机,减少噪音"
                                        preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * action) 
											{
                                                //响应事件
                                                NSLog(@"action = %@", action);
                                            }];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault
                                            handler:^(UIAlertAction * action)
											{
                                                //响应事件
                                                NSLog(@"action = %@", action);
                                            }];
            [alert addAction:defaultAction];
            [alert addAction:cancelAction];
            //[self presentViewController:alert animated:YES completion:nil];
            
            UIViewController *viewController = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
            if ( viewController.presentedViewController && !viewController.presentedViewController.isBeingDismissed )
            {
                viewController = viewController.presentedViewController;
            }
            
            NSLayoutConstraint *constraint = [NSLayoutConstraint
                                              constraintWithItem:alert.view
                                              attribute:NSLayoutAttributeHeight
                                              relatedBy:NSLayoutRelationLessThanOrEqual
                                              toItem:nil
                                              attribute:NSLayoutAttributeNotAnAttribute
                                              multiplier:1
                                              constant:viewController.view.frame.size.height*2.0f];
            
            [alert.view addConstraint:constraint];
            [viewController presentViewController:alert animated:YES completion:^{}];
        }
    }
}

unity中应用:

[DllImport("__Internal")]
private static extern void ShowAlert();
//然后在需要的地方调用 ShowAlert()

你可能感兴趣的:(unity,iOS)