flutter ios permission_handle权限动态申请

网上都是针对安卓的教程,以下是作者使用Flutter打包在iphone上运行动态申请权限的实战记录。

项目在:https://github.com/xmcy0011/CoffeeChat

开源IM解决方案,包含服务端(go)和客户端(Flutter)。单聊和机器人(小微、图灵、思知)聊天功能已完成,目前正在研发群聊功能。

配置

permission_handle

在pubspec.yaml中增加

dependencies:
  flutter:
    sdk: flutter

  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  ...
  permission_handler: ^3.0.0  # 权限

Android项目

AndroidManifest.xml中增加:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.coffeechat.cc_flutter_app">

    <!-- io.flutter.app.FlutterApplication is an android.app.Application that
         calls FlutterMain.startInitialization(this); in its onCreate method.
         In most cases you can leave this as-is, but you if you want to provide
         additional functionality it is fine to subclass or reimplement
         FlutterApplication and put your custom class here. -->
    <application
        android:name="io.flutter.app.FlutterApplication"
        android:label="CoffeeChat"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- This keeps the window background of the activity showing
                 until Flutter renders its first frame. It can be removed if
                 there is no splash screen (such as the default splash screen
                 defined in @style/LaunchTheme). -->
            <meta-data
                android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
                android:value="true" />
            <intent-filter>
                <action android:name="android.permission.INTERNET"/>

				# 你的权限
				# 我这边申请了,摄像头和麦克风
				# 列表在https://pub.flutter-io.cn/packages/permission_handler
				# “List of available permissions” 一节
                <action android:name="android.permission.CAMERA"/>
                <action android:name="android.permission.Microphone"/>
                
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
    </application>
</manifest>

IOS项目

1.Podfile中增加

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'

	  # 以下是新增的,permission_handle中动态申请摄像头、麦克风权限
	  # 权限列表参考:https://pub.flutter-io.cn/packages/permission_handler
	  # "Add the following to your Podfile file" 一节
	  
      # You can remove unused permissions here
      # for more infomation: https://github.com/BaseflowIT/flutter-permission-handler/blob/develop/ios/Classes/PermissionHandlerEnums.h
      # e.g. when you don't need camera permission, just add 'PERMISSION_CAMERA=0'
      config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= [
        '$(inherited)',
        ## dart: PermissionGroup.camera
       'PERMISSION_CAMERA=0',

        ## dart: PermissionGroup.microphone
       'PERMISSION_MICROPHONE=0',
      ]
    end
  end
end

2.Info.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CFBundleDevelopmentRegion</key>
	<string>$(DEVELOPMENT_LANGUAGE)</string>
	<key>CFBundleExecutable</key>
	<string>$(EXECUTABLE_NAME)</string>
	<key>CFBundleIdentifier</key>
	<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
	<key>CFBundleInfoDictionaryVersion</key>
	<string>6.0</string>
	<key>CFBundleName</key>
	<string>CoffeeChat</string>
	<key>CFBundlePackageType</key>
	<string>APPL</string>
	<key>CFBundleShortVersionString</key>
	<string>$(FLUTTER_BUILD_NAME)</string>
	<key>CFBundleSignature</key>
	<string>????</string>
	<key>CFBundleVersion</key>
	<string>$(FLUTTER_BUILD_NUMBER)</string>
	<key>LSRequiresIPhoneOS</key>
	<true/>

    # 这里是新增的,具体参考https://pub.flutter-io.cn/packages/permission_handler
    # “Delete the corresponding permission description in Info.plist” 一节
    # 这里申请摄像头和麦克风,如果Info.plist不添加这4行,将直接崩溃
	<key>NSCameraUsageDescription</key>
    <string>The app tries to use your camera</string>
    <key>NSMicrophoneUsageDescription</key>
    <string>The app tries to use your microphone</string>

	<key>UILaunchStoryboardName</key>
	<string>LaunchScreen</string>
	<key>UIMainStoryboardFile</key>
	<string>Main</string>
	<key>UISupportedInterfaceOrientations</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UISupportedInterfaceOrientations~ipad</key>
	<array>
		<string>UIInterfaceOrientationPortrait</string>
		<string>UIInterfaceOrientationPortraitUpsideDown</string>
		<string>UIInterfaceOrientationLandscapeLeft</string>
		<string>UIInterfaceOrientationLandscapeRight</string>
	</array>
	<key>UIViewControllerBasedStatusBarAppearance</key>
	<false/>
</dict>
</plist>

代码

关键代码如下

_handleCameraAndMic() async {
    // 请求权限
    Map<PermissionGroup, PermissionStatus> permissions = await PermissionHandler().requestPermissions(
      [PermissionGroup.camera, PermissionGroup.microphone],
    );

    //校验权限
    if (permissions[PermissionGroup.camera] != PermissionStatus.granted) {
      print("无照相权限");
      return false;
    }
    if (permissions[PermissionGroup.microphone] != PermissionStatus.granted) {
      print("无麦克风权限");
      return false;
    }
    return true;
  }

void _onVoiceCall() async {
    // await for camera and mic permissions before pushing video page
    if (await _handleCameraAndMic()) {
      navigatePushPage(this.context,
          new PageAVChatCallerStatefulWidget(Int64(this.sessionInfo.sessionId), this.sessionInfo.sessionName));
    }
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章