如何在fcm-django中为iOS平台的APNs添加Badge值?
解决fcm-django中iOS APNs Badge值设置问题
你之前的错误核心是**Message的apns参数传参方式错误**:该参数需要接收APNSConfig对象,而非直接传入Aps实例。以下是两种正确的实现方案:
方案一:直接在FCMNotification中设置Badge
如果仅需简单配置badge值,最直接的方式是将badge加入FCMNotification参数,FCM会自动映射到APNs的对应字段:
from fcm_django.models import FCMDevice from firebase_admin.messaging import Message, FCMNotification from rest_framework.response import Response from rest_framework import status def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more", "badge": 10 # 直接添加整数类型的badge值 } extra_data = {"type": "some information", "link": "https://google.com"} for device in devices: try: if device.type == "ios": device.send_message(Message( notification=FCMNotification(**body_data), data=extra_data )) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK)
方案二:通过APNSConfig自定义APNs专属参数
如果需要配置更多APNs特性(如音效、静默推送),可以用APNSConfig和Aps组合实现:
from fcm_django.models import FCMDevice from firebase_admin.messaging import Message, FCMNotification, APNSConfig, Aps from rest_framework.response import Response from rest_framework import status def get(self, request, *args, **kwargs): user = request.user devices = FCMDevice.objects.filter(user=user) body_data = { "title": "Title text", "body": "Click to explore more" } extra_data = {"type": "some information", "link": "https://google.com"} for device in devices: try: if device.type == "ios": apns_config = APNSConfig( aps=Aps( badge=10, sound="default", # 可选:设置通知音效 content_available=True # 可选:开启静默推送支持 ) ) device.send_message(Message( notification=FCMNotification(**body_data), data=extra_data, apns=apns_config # 传入APNSConfig实例 )) else: device.send_message(Message(data={**body_data, **extra_data})) except Exception as e: return Response({'error_message': str(e)}, status=status.HTTP_400_BAD_REQUEST) return Response(status=status.HTTP_200_OK)
重要注意点
- badge值必须是整数类型,不能传字符串(你之前的
str(10)会导致参数无效); - 避免在
extra_data中重复传入badge,防止参数冲突; - 使用
APNSConfig时,必须确保导入对应类,且apns参数仅接收APNSConfig实例。
内容的提问来源于stack exchange,提问作者Anna Berezko
相关产品推荐
相关产品推荐

