Firebase Storage获取图片下载URL耗时过长及App Check报错求助
Firebase Storage获取下载URL耗时久,伴随App Check认证失败报错
现象
图片上传Firebase Storage速度正常,但调用getDownloadURL()要等5秒左右,控制台还弹出两个报错:
Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Error returned from API. code: 403 body: App attestation failed.
Error getting App Check token; using placeholder token instead. Error: com.google.firebase.FirebaseException: Too many attempts.
代码能正常完成上传和把URL存到Firestore,但不确定这些报错是不是拖慢了getDownloadURL()的速度,查了帖子也没解决。
我用的代码
上传图片方法
Future<String?> uploadImage( XFile image, String docId, context) async { try { checkConnection(context); Reference storageRef = bucketReference.child('$type/$docId.jpg'); await storageRef.putFile(File(image.path)); print('image uploaded ////////////////'); final downloadUrl = await storageRef.getDownloadURL(); print('got download url ////////////////'); return downloadUrl; } on FirebaseException catch (e) { print(e); showSnackbarMessage(context, upload, 0); return null; } }
保存到Firestore方法
Future<void> save( String? note, XFile? image, context, ) async { String? imageUrl; String incomeDocID = incomeCollectionRef.doc().id; try { if (image != null) { imageUrl = await uploadImage(image, incomeDocID, context); } DocumentReference incomeDocRef = incomeCollectionRef.doc(incomeDocID); incomeDocRef.set({ if (note != null && note.isNotEmpty) 'Note': note, if (imageUrl != null) 'ImageURL': imageUrl, }); print('saved to doc ////////////////'); Navigator.pop(context); } catch (e) { showSnackbarMessage(context, unexpectedError, 2); } }
问题分析和解决办法
报错为啥会拖慢速度?
肯定有关系!Firebase调用getDownloadURL()这种敏感接口时,会先尝试拿有效的App Check Token。一旦认证失败,SDK会反复重试(就是那个"Too many attempts"报错的原因),这个重试过程会卡住getDownloadURL(),直到最后用占位Token,自然就慢了。
怎么解决?
核对App Check配置
- 去Firebase控制台的App Check页面,确认已经给对应平台开了正确的认证服务(Android用SafetyNet,iOS用App Attest/DeviceCheck)。
- 检查Android的SHA-256签名证书、iOS的Bundle ID有没有在控制台填对,要和打包时的一致。
- 调试阶段的话,别忘了加调试设备的App Check Token(控制台能生成)。
换异步方式生成URL(可选)
- 要是不用立即拿到URL,可以用Cloud Function异步处理:
- 图片上传完成后,触发Storage的
onFinalize触发器。 - 在云函数里调用
getSignedUrl()生成下载链接,再写到对应的Firestore文档里,这样前端就不用等了。
- 图片上传完成后,触发Storage的
- 要是不用立即拿到URL,可以用Cloud Function异步处理:
调试时临时关App Check
- 要是只想先排除App Check的影响,初始化Firebase时可以临时用调试模式:
注意:上线前必须换回正式配置,不然安全没保障。await FirebaseAppCheck.instance.activate( androidProvider: DebugAppCheckProvider(), // iOS对应DebugAppCheckProvider()或者其他调试配置 );
- 要是只想先排除App Check的影响,初始化Firebase时可以临时用调试模式:
检查网络
- 有些地区访问Firebase可能有延迟,换个网络试试,或者在控制台把Storage的存储区域改成离你近的。
内容的提问来源于stack exchange,提问作者user8
相关产品推荐
相关产品推荐

