1

AWS AppSync用于创建我的 iOS 应用程序。我想利用离线变异以及AppSync. 但是当我关闭我的互联网时,我没有得到任何回应。而是将错误显示为“Internet 连接似乎已脱机。”。这似乎是一个Alamofire例外而不是AppSync例外。这是因为查询没有缓存在我的设备中。以下是我初始化客户端的代码片段。

do {
    let appSyncClientConfig = try AWSAppSyncClientConfiguration.init(url: AWSConstants.APP_SYNC_ENDPOINT, serviceRegion: AWSConstants.AWS_REGION, userPoolsAuthProvider: MyCognitoUserPoolsAuthProvider())
    AppSyncHelper.shared.appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncClientConfig)
    AppSyncHelper.shared.appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }
} catch {
    print("Error in initializing the AppSync Client")
    print("Error: \(error)")
    UserDefaults.standard.set(nil, forKey: DeviceConstants.ID_TOKEN)
}

我在UserDefaults获取会话时将令牌缓存在 中,然后每当AppSyncClient调用 时,它都会通过调用getLatestAuthToken()my 的方法来获取最新的令牌MyCognitoUserPoolsAuthProvider: AWSCognitoUserPoolsAuthProvider。这将返回存储在UserDefaults-

// background thread - asynchronous
func getLatestAuthToken() -> String {
    print("Inside getLatestAuthToken")
    var token: String? = nil
    if let tokenString = UserDefaults.standard.string(forKey: DeviceConstants.ID_TOKEN) {
        token = tokenString
        return token!
    }
    return token!
}

我的查询模式如下

public func getUserProfile(userId: String, success: @escaping (ProfileModel) -> Void, failure: @escaping (NSError) -> Void) {
    let getQuery = GetUserProfileQuery(id: userId)
    print("getQuery.id: \(getQuery.id)")
    if appSyncClient != nil {
        print("AppSyncClient is not nil")
        appSyncClient?.fetch(query: getQuery, cachePolicy: CachePolicy.returnCacheDataElseFetch, queue: DispatchQueue.global(qos: .background), resultHandler: { (result, error) in
            if error != nil {
                failure(error! as NSError)
            } else {
                var profileModel = ProfileModel()
                print("result: \(result)")
                if let data = result?.data {
                    print("data: \(data)")
                    if let userProfile = data.snapshot["getUserProfile"] as? [String: Any?] {
                        profileModel = ProfileModel(id: UserDefaults.standard.string(forKey: DeviceConstants.USER_ID), username: userProfile["username"] as? String, mobileNumber: userProfile["mobileNumber"] as? String, name: userProfile["name"] as? String, gender: (userProfile["gender"] as? Gender).map { $0.rawValue }, dob: userProfile["dob"] as? String, profilePicUrl: userProfile["profilePicUrl"] as? String)
                    } else {
                        print("data snapshot is nil")
                    }
                }
                success(profileModel)
            }
        })
    } else {
        APPUtilites.displayErrorSnackbar(message: "Error in the user session. Please login again")
    }
}

我已经使用了 AppSync 提供的所有 4 个 CachePolicy 对象,即

CachePolicy.returnCacheDataElseFetch
CachePolicy.fetchIgnoringCacheData
CachePolicy.returnCacheDataDontFetch
CachePolicy.returnCacheDataAndFetch.

有人可以帮助我为我的 iOS 应用程序正确实现缓存,以便我也可以在没有互联网的情况下进行查询吗?

4

1 回答 1

0

好的,所以我自己找到了答案。databaseUrl 是一个可选参数。当我们初始化 AWSAppSyncClientConfiguration 对象时,它不会出现在建议中。

所以我初始化客户端的新方法如下

let databaseURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(AWSConstants.DATABASE_NAME, isDirectory: false)
    do {
        let appSyncClientConfig = try AWSAppSyncClientConfiguration.init(url: AWSConstants.APP_SYNC_ENDPOINT,
                           serviceRegion: AWSConstants.AWS_REGION,
                           userPoolsAuthProvider: MyCognitoUserPoolsAuthProvider(),
                           urlSessionConfiguration: URLSessionConfiguration.default,
                           databaseURL: databaseURL)
        AppSyncHelper.shared.appSyncClient = try AWSAppSyncClient(appSyncConfig: appSyncClientConfig)

        AppSyncHelper.shared.appSyncClient?.apolloClient?.cacheKeyForObject = { $0["id"] }
    } catch {
        print("Error in initializing the AppSync Client")
        print("Error: \(error)")
    }

希望能帮助到你。

于 2018-09-19T13:28:18.850 回答