flutter_native_splash 사용시 ios에서 전체화면 이안되고 작게나올때 

xcode - Runner -Runner - LaunchScreen - LaunchImage - View - Content Mode를 변경하면 된다 

반응형

android

 

 

android-app-src-main-AndroidManifest.xml로 들어가서  label의 이름을 @string/app_name로 변경

 

 

수동버전

android-app-src-main-res-values에 오른쪽 클릭 후 string.xml 파일 하나 생성

 

 

 

 

다음과 같이 생성  name에 아까 AndroidManifest에서 적은 label 뒷이름과 같게 생성

 

 

 

 

다음과 같이 원하는 언어 (ex 영어는 en) 붙여서 생성하고 앱이름만 영어로하면 완성 

 

 

 

 

android 활용

android studio로 flutter 내의 android를 연다  그후 아래경로에서 label 이름 변경

 

 

 

 

 

values에 string.xml 생성 후  open Translations Editor 클릭

 

 

 

 

 

아래에서 원하는 언어 선택하면 자동으로 추가된다 

 

 

 

 

 

 

자동으로 추가된다  추가된 string에 들어가서 언어만 바꾸면된다 

 

 

 

========================================================================================

ios

 

xcode 실행 후 Runner - Runner Localizations - + 클릭해서 원하는 언어들 셋팅 

 

 

 

 

 

Runner에두고 xcode-File-New-File 클릭

 

 

 

 

string파일 선택 후 넥스트 

 

 

 

 

 

제목을 InfoPlist.strings로 만들고 create 클릭

 

 

 

 

 

생성 후 맨오른쪽 Localize 클릭

 

 

 

 

 

원하는 언어 선택후 생성 

 

 

 

 

 

생성후 맨오른쪽에 localization에 모두 클릭하면 왼쪽에 infoPilst안에 각각언어로 생성된다 

 

 

 

 

 

 

언어별 InfoPlist파일에 "CFBundleDisplayName"="원하는앱이름"; 추가하면 끝

 

 

반응형

'flutter' 카테고리의 다른 글

fireabase 연동  (2) 2022.09.22
firebase export PATH="$PATH":"$HOME/.pub-cache/bin  (0) 2022.09.22
mac os에 flutter 설치  (0) 2021.07.17

날씨 라이브러리인 accuweather를 써보려는데 

사이트내에서 앱을 만들고 api키로 이것저것 써보려는데 401이 자꾸났다.

 

그럴땐 만든 앱의 셋팅값을 아래와 같이하면 된다 

 

https://github.com/home-assistant/core/issues/61812

반응형

firebase문제로 이 에러가 발생하였다

firebase_core_platform_interface: 4.5.1이부분을 지우고

firebase desktop 라이브러리 몇개 지우고 

업데이트하니 정상작동한다.

 

 

업데이트 할수있는 패키지를 찾는다

flutter pub outdated

 

낮은버전 패키지 모두 업데이트

flutter pub upgrade --major-versions

 

참고:https://www.wafrat.com/fixing-error-method-not-found-fallthrougherror-load_bundle_task_state-dart-17-throw-fallthrougherror-target-kernel_snapshot-failed-exception/

반응형

android studio쓰면 run 클릭시 크롬으로 바로 볼수가있는데 (flutter run -d chrome)

 

web으로 만든것을 같은 wifi내에 공유하려면 서버를 띄워야한다.

 

1. web 빌드

flutter build web

 

 

2. 프로젝트 build/web로 이동

cd build/web 후 

python -m http.server [포트번호]   ex) python -m http.server 50000 (mac은 python 기본탑제,window는 깔아야함)

 

같은 wifi내에서 접속가능하다

반응형

Command PhaseScriptExecution failed with a nonzero exit

xcode 14.3으로 업그레이드 이후 위와 같은 에러가 생겼다면 

 

xcode 검색 -> symlinked 검색 후 첫번째꺼 클릭-> readlink 뒷부분에 -f 를 추가하면 된다 

 

참고:https://www.youtube.com/watch?v=h3YOJKQooPo

반응형

'flutter > ios' 카테고리의 다른 글

ios 스플래시 사용시 전체화면  (0) 2024.03.21
adb command not found  (0) 2023.02.02
Xcode doesn’t support iPhone’s iOS  (0) 2022.09.22
ios 기기 인식 못할때  (1) 2021.11.13
ios appstore reject 10번이상 리젝맞은 사유 모음  (0) 2021.10.15

flutter에서 push를 보내려면

2가지 라이브러리를 써야한다.

https://pub.dev/packages/flutter_local_notifications

https://pub.dev/packages/firebase_messaging

 

실질적으로 창을 띄우는역활을 하는 flutter_local_notifications와

데이터를 받는부분의 firebase_messaging

 

 

flutter_local_notifications의 android 셋팅

flutter-android-build.gradle에 

com.android.tools.build.gradle은 최소 4.2.2를 써야하고 (이보다 높으면 놔둬라)

buildscript {
   ...

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.2'
        ...
    }

 

 

flutter-android-app-src-build.gradle에 들어가서 각각 부분에 아래정보들을 복붙한다.

android {
  compileSdkVersion 33 // 최소 33이상이여야한다
  defaultConfig {
    multiDexEnabled true
  }

  compileOptions {
    // Flag to enable support for the new language APIs
    coreLibraryDesugaringEnabled true
    // Sets Java compatibility to Java 8
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

dependencies {
  implementation 'androidx.window:window:1.0.0'
  implementation 'androidx.window:window-java:1.0.0'
  coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:1.1.5'
}

 

flutter-android-app-src-main-AndroidManifest.xml 에 들어가서 

MainActivity에다 아래정보 추가 showWhenLocked,trunScreenOn true 추가

<activity
    android:name=".MainActivity"
    android:showWhenLocked="true"
    android:turnScreenOn="true">

 

 

flutter_local_notifications의 ios셋팅

xcode-Runner-Runner-AppDelegate에 들어가서 값추가

if #available(iOS 10.0, *) {
  UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

예시)

import UIKit
import Flutter
import flutter_local_notifications

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    // This is required to make any communication available in the action isolate.
    FlutterLocalNotificationsPlugin.setPluginRegistrantCallback { (registry) in
        GeneratedPluginRegistrant.register(with: registry)
    }

    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as UNUserNotificationCenterDelegate
    }

    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

 

 

fcm의 ios셋팅

ios개발자 - certificates,Identifiers&Profiles에 들어가서 Identifiers- 본인프로젝트 클릭 

 

쭉내리다보면 Push Notifications 발견하면 클릭후 저장한다

 

 

 

 

xcode로 와서Runner-Signing& Capabilities에 Capability버튼 클릭

 

push와 back ground modes를 검색하여 더블클릭해서 추가한다.

 

 

 

Background fetch에 체크하면된다 

그리고 

 

xcode-Runner-runner-info에서 FirebaseAppDelegateProxyEnabled No로 추가해야 로그에 에러가안뜬다 

 

 

 

 

 

이제 apn 설정 

ios개발자 - certificates,Identifiers&Profiles에 keys에 들어가서 +를 누른다

 

 

 

Apple Push Notifications service (APNs)를 클릭후 원하는이름 지정 후 다음

 

 

건들것없다 생성

 

 

 

이제 만든키를 다운받고 key id를 복사해놓는다 

 

 

 

 

firebase프로젝트 설정 - 클라우드 메시징 - apple 앱 구성에 apn 인증서 업로드 클릭

 

 

 

 

아래와같이 찾아보기 클릭 후 아까 다운받은 인증서 클릭해서 넣고 복사한키도 같이 붙여넣는다.

팀id는 firebase에 미리넣어둔사람은 바로뜨는데 안넣어놔서 안떴다면 

ios개발자 - certificates,Identifiers&Profiles에 들어가서 Identifiers- 본인프로젝트 클릭 들어가면 App ID Prefix라고 뜨는데 이거다

 

 

 

 

업로드하면 아래와같이 들어가져있다

 

 

 

앱에서 푸쉬를 받는 상황은 

앱켜진상태 background,foreground

앱이 꺼진상태

 

 

flutter-main안에 추가

  //앱이 꺼졌을때 //앱 백그라운드
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  //앱 포그라운드
  FirebaseMessaging.onMessage.listen(
    showFlutterNotification,
  );

  //앱 백그라운드에서 푸쉬클릭시
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    Get.toNamed(message.data.keys.first,
        arguments: int.parse(message.data.values.first));
  });

  //앱꺼진상태에서 푸시클릭시 이동
  FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
    if (message != null) {
      Get.toNamed(message.data.keys.first,
          arguments: int.parse(message.data.values.first));
    }
  });
  if (!kIsWeb) {
    await setupFlutterNotifications();
  }

 

 

 

 

background 셋팅부분

  //앱이 꺼졌을때 //앱 백그라운드
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await setupFlutterNotifications();
  // showFlutterNotification(message);firebase에서 자동으띄워줌(주석지우면 2번뜸)
}

background 클릭 이벤트부분

//앱 백그라운드에서 푸쉬클릭시
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
  Get.toNamed(message.data.keys.first,
      arguments: int.parse(message.data.values.first));
});

 

 

 

 

 

foreground셋팅부분 

FirebaseMessaging.onMessage.listen(
  showFlutterNotification,
);
void showFlutterNotification(RemoteMessage message) {
  RemoteNotification? notification = message.notification;
  AndroidNotification? android = message.notification?.android;
  if (notification != null && android != null && !kIsWeb) {
    flutterLocalNotificationsPlugin.show(
      notification.hashCode,
      notification.title,
      notification.body,
      payload: jsonEncode(message.data),//필수 
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          channelDescription: channel.description,
          // TODO add a proper drawable resource to android, for now using
          //      one that already exists in example app.
          icon: '@mipmap/launcher_icon',
        ),
      ),
    );
  }
}

foreground 클릭 이벤트부분

//setupFlutterNotifications안에 onDidReceiveNotificationResponse 이부분이다

  flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onDidReceiveBackgroundNotificationResponse: onSelectNotification,
    onDidReceiveNotificationResponse: onSelectNotification,
  );
onSelectNotification(NotificationResponse details) async {
  if (details.payload != null) {
    Map<String, dynamic> data = jsonDecode(details.payload ?? "");
    Get.toNamed(data.keys.first, arguments: int.parse(data.values.first));
  }
}

 

 

 

 

 

앱꺼졌을시

셋팅부분(백그라운드와 중복)

  //앱이 꺼졌을때 //앱 백그라운드
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await setupFlutterNotifications();
  // showFlutterNotification(message);firebase에서 자동으띄워줌(주석지우면 2번뜸)
}

앱꺼졌을시

클릭 이벤트부분

//앱꺼진상태에서 푸시클릭시 이동
FirebaseMessaging.instance.getInitialMessage().then((RemoteMessage? message) {
  if (message != null) {
    Get.toNamed(message.data.keys.first,
        arguments: int.parse(message.data.values.first));
  }
});

 

 

 

 

 

기본셋팅부분

Future<void> setupFlutterNotifications() async {
  if (isFlutterLocalNotificationsInitialized) {
    return;
  }
  channel = const AndroidNotificationChannel(
    'high_importance_channel', // id
    'High Importance Notifications', // title
    description: 'This channel is used for important notifications.',
    // description
    importance: Importance.high,
  );

  var initializationSettingsAndroid =
      const AndroidInitializationSettings('@mipmap/launcher_icon');

  var initializationSettingsIos = const DarwinInitializationSettings();

  var initializationSettings = InitializationSettings(
    android: initializationSettingsAndroid,
    iOS: initializationSettingsIos,
  );

  flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  flutterLocalNotificationsPlugin.initialize(
    initializationSettings,
    onDidReceiveBackgroundNotificationResponse: onSelectNotification,
    onDidReceiveNotificationResponse: onSelectNotification,
  );

  /// Create an Android Notification Channel.
  ///
  /// We use this channel in the `AndroidManifest.xml` file to override the
  /// default FCM channel to enable heads up notifications.
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);

  /// Update the iOS foreground notification presentation options to allow
  /// heads up notifications.
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
  isFlutterLocalNotificationsInitialized = true;
}

 

 

 

 

 

이제 파이어베이스 콘솔-Messaging으로 가서 첫 번째 캠페인 만들기 클릭

 

 

 

 

첫번째꺼 클릭 후 만들기

 

 

 

 

푸쉬로 보낼 제목과 텍스트를 입력 

 

 

 

 

타겟에서 안드로이드와 ios 원하는것 선택 

 

 

 

예약하고싶으면 설정하고

이동하고싶은 경로가 있으면 추가옵션에 맞춤데이터에 값을 넣는다.

다 설정후 절대 검토를 누르면 안된다!!! 실제로 날라감

 

 

검토 대신 다시 알림으로 돌아가서 테스트메시지 전송을 눌르면 된다 

 

 

 

 

누르면 아래와같이 뜨는데 FCM 등록 토큰 추가 이부분에 클릭해서  토큰을 추가해야한다 

앱의 토큰 보는방법은

var token = await FirebaseMessaging.instance.getToken();

token값을 아래에 넣으면 된다 

 

 

 

그리고 체크 후 테스트 누르면 푸쉬가 매우 잘 날라온다.

 

 

테스트할때는 ios는 무조건 실제폰에서 android는 에뮬레이터로 된다 앱이 꺼졌을때 테스트시 android는 release모드로 빌드해서 테스트해야한다 

반응형

'flutter > study' 카테고리의 다른 글

firebase dynamiclink 만들기  (0) 2023.03.03
google map 연동  (0) 2022.09.25
money comma  (0) 2021.11.05
flutter 현지화  (0) 2021.07.28
TextField 사용시 바깥부분 터치시 focus 잃게하는방법  (0) 2021.07.28

링크를 누르면 앱내의 특정페이지로 가게끔 작업하자

 

다이나믹링크 패키지 설치 

https://pub.dev/packages/firebase_dynamic_links

 

링크 만드는방법중 파이어베이스 내에서 만드는방법과 코드로 따로만드는방법이있는데 

코드로 만들어야 유동적인 파라미터값을 넣을수 있어서 코드로 만드는방법을 사용한다.

 

 

링크생성부분

final dynamicLinkParams = DynamicLinkParameters(
  link: Uri.parse("https://www.example.com/?name='hoho'&age='30' "), //이름과 나이를 파라미터로
  uriPrefix: "https://example.page.link",//파베에있는 https://page.link로 끝나는 메인링크
  androidParameters: const AndroidParameters(packageName: "com.example.app"),
  iosParameters: const IOSParameters(bundleId: "com.example.app"),
);
final dynamicLink =
    await FirebaseDynamicLinks.instance.buildShortLink(dynamicLinkParams);

 

링크생성 완료 

 

 

 

 

앱 링크받을 셋팅

링크를 열기위한 셋팅을 먼저 해줘야한다.

android

android-app-src-main-AndroidManifest.xml로 들어가서

<intent-filter>
    <action android:name="android.intent.action.VIEW"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <category android:name="android.intent.category.BROWSABLE"/>
    <data
        android:host="example.com"
        android:scheme="https"/>
</intent-filter>

application-activity안에 넣는다 

 

<application
    android:name="${applicationName}"
    android:icon="@mipmap/launcher_icon"
    android:usesCleartextTraffic="true">
    <activity
        android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:exported="true"
        android:hardwareAccelerated="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:windowSoftInputMode="adjustResize">
        <meta-data
            android:name="io.flutter.embedding.android.NormalTheme"
            android:resource="@style/NormalTheme" />

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <category android:name="android.intent.category.BROWSABLE"/>
            <data
                android:host="example.page.link" //파베에있는메인주소
                android:scheme="https"/>
        </intent-filter>
    </activity>

 

ios

xcode로 들어가서 

Runner - Singning & Capabilities - +Capability클릭하여 Associated Domains를 추가한다 

domains에 applinks:파베에있는메인주소

ex)applinks:example.page.link을 추가한다

 

 

 

 

링크받는부분

이제 main에서 꺼진상태에서 값받는부분과 포,백그라운드 상태서 값받는부분을 넣고 

//앱꺼졌을시
final PendingDynamicLinkData? initialLink = await FirebaseDynamicLinks.instance.getInitialLink();
handleLinkData(initialLink);

//포그라운드,백그라운드용
FirebaseDynamicLinks.instance.onLink.listen((dynamicLinkData) {
  handleLinkData(dynamicLinkData);
}).onError((error) {
  print("@@dynamic link listen error=${error}");
});
void handleLinkData(PendingDynamicLinkData? data) {
  final Uri? uri = data?.link;
  if (uri != null) {
    final queryParams = uri.queryParameters;
    if (queryParams.isNotEmpty) {
      String? name = queryParams["name"];
      String? age = queryParams["age"];
      if (name != null) {
        //name with 이동처리 
      }
      if (age != null) {
        //age with 이동처리
      }
      // verify the username is parsed correctly
      print("@@My name is: $name / age is $age");
    }
  }
}

 

만약 셋팅이 잘못되었다면

 

앱이 깔려있어도 앱에 접속이안되고 다운받는 스토어로 갈것이다.

 

 

참고:

https://firebase.google.com/docs/dynamic-links/flutter/create?hl=ko

https://firebase.google.com/docs/dynamic-links/flutter/receive?hl=ko

반응형

'flutter > study' 카테고리의 다른 글

flutter fcm push  (0) 2023.03.30
google map 연동  (0) 2022.09.25
money comma  (0) 2021.11.05
flutter 현지화  (0) 2021.07.28
TextField 사용시 바깥부분 터치시 focus 잃게하는방법  (0) 2021.07.28

ios

xcode - Runner-AppDelegate.swift에 들어간다 

 

import UIKit
import Flutter
import GoogleMaps

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    self.window.makeSecure()
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
    override func applicationWillResignActive(
      _ application: UIApplication
    ) {
      self.window.isHidden = true;
    }
    override func applicationDidBecomeActive(
      _ application: UIApplication
    ) {
      self.window.isHidden = false;
    }

}
  extension UIWindow {
    func makeSecure() {
     let field = UITextField()
     field.isSecureTextEntry = true
     self.addSubview(field)
     field.centerYAnchor.constraint(equalTo: self.centerYAnchor).isActive = true
     field.centerXAnchor.constraint(equalTo: self.centerXAnchor).isActive = true
     self.layer.superlayer?.addSublayer(field.layer)
     field.layer.sublayers?.first?.addSublayer(self.layer)
   }
 }

 

빨간 부분을 추가하면 캡쳐서 검은화면으로 나온다.

 

 

android

https://pub.dev/packages/flutter_windowmanager/example

라이브러리 설치 후 main에 넣는다

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE);
  runApp(MyApp());
}

 

캡처시 문구가뜬다.

 

 

참고:
https://stackoverflow.com/questions/52317217/flutter-disable-screenshot-capture-for-app

https://stackoverflow.com/questions/72380810/how-to-prevent-taking-screen-shoot-in-flutter-ios

반응형

 

flutter 만깔고 터미널에 adb명령어를 치면 adb command not found 이라고 뜬다면

 

finder- 자기계정폴더 - command+ shift + . 을 눌러서 숨겨진 폴더보기 활성화 후 

zprofile을 찾아서 연 후 

export PATH=~/Library/Android/sdk/tools:$PATH
export PATH=~/Library/Android/sdk/platform-tools:$PATH

값을 넣고 저장 

source ~/.zprofile

입력하면 adb 명령어가 발동

 

 

참고:https://stackoverflow.com/questions/10303639/adb-command-not-found

반응형

+ Recent posts