【问题标题】:Is it possible to get the stored data from react-native-async-storage in Swift?是否可以从 Swift 中的 react-native-async-storage 获取存储的数据?
【发布时间】:2022-01-02 18:43:02
【问题描述】:

我在 AppStore 中有一个用 React-Native 制作的应用。我现在选择用 Swift 而不是 React-native 重写整个应用程序。

我的问题是是否可以访问存储在设备上的数据并在 Swift 中检索它。我已将用户的登录令牌存储在 react-native-async-storage 中,并且我需要在 Swift 中使用该令牌,以便用户在更新到应用程序的新版本时保持登录状态。

我在 React-Native 中的代码:

if (responseJson.status && responseJson.token && responseJson.login) {

        await AsyncStorage.setItem('@logged_in', 'true');
        await AsyncStorage.setItem('@token', responseJson.token);
}

我真的希望可以做到。该应用在登录时会发送一条确认短信,由于该应用的用户非常多,因此很快就会花费很多钱。

【问题讨论】:

标签: ios swift react-native


【解决方案1】:

我找到了解决办法:

func getTokenFromReactNative() -> String? {

    let RCTStorageDirectory = "RCTAsyncLocalStorage_V1"
    let RCTManifestFileName = "manifest.json"

    let fileManager = FileManager.default

    let appSupportDirectory = fileManager.urls(for: .applicationSupportDirectory, in: .userDomainMask).first

    let mySupportDirectory = appSupportDirectory!.appendingPathComponent(Bundle.main.bundleIdentifier!)

    let storageDirectory = mySupportDirectory.appendingPathComponent(RCTStorageDirectory)

    let storageFile = storageDirectory.appendingPathComponent(RCTManifestFileName)

    if fileManager.fileExists(atPath: storageFile.path) {

        do {

            let stringFromFile = try String(contentsOf: storageFile, encoding: .utf8)

            let data = stringFromFile.data(using: .utf8, allowLossyConversion: false)

            let json = try? JSONSerialization.jsonObject(with: data!, options: .mutableContainers)

            let dict = json as? [String: String]

            return dict?["@token"] ?? nil

        }
        catch {

            return nil

        }

    }
    
    return nil
    
}

【讨论】:

    猜你喜欢
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2019-08-26
    相关资源
    最近更新 更多