为AWS AppSync客户端iOS Swift启用缓存

时间:2018-09-17 20:32:38

标签: ios swift caching aws-appsync aws-appsync-ios

我正在使用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()方法来获取最新令牌我的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应用正确实现缓存,以便我也可以在没有互联网的情况下进行查询吗?

1 个答案:

答案 0 :(得分: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)")
    }

希望有帮助。