FCM, Firebase Cloud Messagin 연동 에서 이어지는 내용이기 때문에, fcm 관련 세팅이 완료되어있어야 합니다.
token = await FirebaseMessaging.instance.getToken();
사실 저번에 진행했던 세팅이 완료되면 앱에서 알림보내는것은 어렵지 않았다.
class FCMController {
final String _serverKey = "your serverKey";
Future<void> sendMessage({
required String userToken,
required String title,
required String body,
}) async {
http.Response response;
NotificationSettings settings =
await FirebaseMessaging.instance.requestPermission(
alert: true,
announcement: false,
badge: true,
carPlay: false,
criticalAlert: false,
provisional: false,
sound: false,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
print('User granted permission');
} else if (settings.authorizationStatus ==
AuthorizationStatus.provisional) {
print('User granted provisional permission');
} else {
print('User declined or has not accepted permission');
}
try {
response = await http.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization': 'key=$_serverKey'
},
body: jsonEncode({
'notification': {'title': title, 'body': body, 'sound': 'false'},
'ttl': '60s',
"content_available": true,
'data': {
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'id': '1',
'status': 'done',
"action": '테스트',
},
// 상대방 토큰 값, to -> 단일, registration_ids -> 여러명
'to': userToken
// 'registration_ids': tokenList
}));
} catch (e) {
print('error $e');
}
}
}
@override
void initState() {
FirebaseMessaging.onMessage.listen((RemoteMessage message) async {
RemoteNotification? notification = message.notification;
AndroidNotification? android = message.notification?.android;
var androidNotiDetails = AndroidNotificationDetails(
channel.id,
channel.name,
channelDescription: channel.description,
);
var iOSNotiDetails = const IOSNotificationDetails();
var details =
NotificationDetails(android: androidNotiDetails, iOS: iOSNotiDetails);
if (notification != null) {
flutterLocalNotificationsPlugin.show(
notification.hashCode,
notification.title,
notification.body,
details,
);
}
});
onMessageOpenedApp((message) {
print("onMessage ${message.data["action"].toString()}");
});
super.initState();
}
When does a FCM token expire? 을 확인해보면 FCM 토큰 값은 다음 중 하나가 발생하면 자체적으로 갱신이 된다고 한다.
token 값이 바뀌면 알림이 보내지지 않기 때문에 token 값 관리가 매우 중요하다.