试图缓存Alamofire没有结果

时间:2016-09-29 21:47:53

标签: swift caching alamofire

我试图使用Alamofire Cache,所以我希望的行为是第一次从网络加载,下次如果数据存在于缓存上,则返回它而不会提出更多请求...在我之后想想到期......

我的代码返回总是响应nil ...对此有任何建议吗?感谢

    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.URLCache = NSURLCache.sharedURLCache()
    config.requestCachePolicy = NSURLRequestCachePolicy.ReturnCacheDataElseLoad
    let manager = Alamofire.Manager(configuration: config)
    manager.request(.GET, url, parameters: parameters, encoding: .URL, headers: ["Token":LocalStorage.read("token") as! String, "Version":"2"]).responseJSON { (response) in

        if let json = response.result.value
        {
            if response.response?.statusCode == 200
            {
                completionHandler(parser.parseSwifty(JSON(json)), nil)
            }
            else
            {
                completionHandler(nil, serverErrorMessage)
            }
        }
        else
        {
            completionHandler(nil, networkErrorMessage)
        }

    }

2 个答案:

答案 0 :(得分:0)

所以......我解决了这个问题: 在我的NetworkHelper中,我添加了一个计算属性,如:

    static let manager: Manager = {
    let memoryCapacity = 100 * 1024 * 1024; // 100 MB
    let diskCapacity = 100 * 1024 * 1024; // 100 MB
    let cache = NSURLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "shared_cache")

    let configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    configuration.HTTPAdditionalHeaders = ["Token":LocalStorage.read("token") as! String, "Version":"2"]
    configuration.requestCachePolicy = .ReturnCacheDataElseLoad // this is the default
    configuration.URLCache = cache

    return Manager(configuration: configuration)
}()

当我必须检索一些数据时:

        self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
        .response { (request, response, data, error) in
            debugPrint(request)
            debugPrint(response)
            debugPrint(error)
    }.responseJSON......

我还写了一个func来预加载一些这样的数据:

    static func preloadGetRequest(url : String, parameters: Dictionary<String, String>?)
{
    self.manager.request(.GET, url, parameters: parameters, encoding: .URL)
        .response { (request, response, data, error) in
            debugPrint(request)
            debugPrint(response)
            debugPrint(error)
    }
}

试着让我知道:)。

答案 1 :(得分:0)

似乎正确的方法是在调用请求之前及早创建会话管理器,否则请求将始终返回nil。

var sessionManager: SessionManager!
override func viewDidLoad() {
    let configuration = URLSessionConfiguration.default
    configuration.requestCachePolicy = .returnCacheDataElseLoad
    sessionManager = SessionManager(configuration: configuration)
}

//later on
@objc private func refreshWeatherData(_ sender: Any) {
    // Fetch Weather Data
    sessionManager.request("https://jsonplaceholder.typicode.com/posts")
    .response { (data) in
        self.refreshControl?.endRefreshing()
        if let data = data.data {
            let json = try? JSON(data: data)
        }
    }
}

或使用类似的缓存策略创建URLRequest

@objc private func refreshWeatherData(_ sender: Any) {
    // Fetch Weather Data
    let request = URLRequest(url: URL(string: "https://jsonplaceholder.typicode.com/posts")!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 100)        
    Alamofire.request(request)
    .response { (data) in
        self.refreshControl?.endRefreshing()
        if let data = data.data {
            let json = try? JSON(data: data)
        }
    }
}