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));
    }
  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章