Fetch API 无法与 Proguard 一起使用

Fetch API not working with Proguard

当混淆器打开时,获取 API 不起作用。下面是代码片段

try {
const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': "application/json",
        'Accept': 'application/json'
      }
    });    
} catch (err) {
  console.log(err)
}

我能够跟踪调试器直到获取调用。但在那之后既没有错误也没有响应。控制台中也没有 errors/warnings。非常感谢任何有关如何 debug/solve 的帮助。

我正在使用 RN v0.55.4(最新)

fetch() 方法采用一个强制参数,即您要获取的资源的路径。它 returns 一个解决该请求响应的 Promise,无论它是否成功。

you need to modify like below

fetch(url)
  .then((resp) => resp.json()) // Transform the data into json
  .then(function(data) {
    // your code logic with the response
    })
  })

添加了以下 proguard 规则来解决此问题

-optimizations !method/*/*,!code/*/*

当 Proguard 启用时(Android 发布版本默认启用),它可以在缩小过程中重命名 BuildConfig Java class 并防止 Fetch 引用它.

为避免这种情况,请在 android/app/proguard-rules.pro:

中添加一个例外
 -keep class com.mypackage.BuildConfig { *; }

此包名称应与您应用的包名称相同。

同时添加 Okhttp3 和 Okio 的 Progurad 规则。

React Native 项目的最终混淆器可能看起来像这样

-keep public class com.horcrux.svg.** {*;}
-keep class com.facebook.react.turbomodule.** { *; }

-dontwarn okio.**
-keep class com.swiggyvendorapp.BuildConfig { *; }
-dontwarn com.squareup.okhttp.**
-keep class com.squareup.okhttp.** { *; }
-keep interface com.squareup.okhttp.** { *; }
-dontwarn retrofit.**
-dontwarn retrofit.appengine.UrlFetchClient
-keep class retrofit.** { *; }
-keepclasseswithmembers class * {
    @retrofit.http.* <methods>;
}
-keepattributes Signature
-keepattributes *Annotation*