我正在尝试找到解决方案,以简单处理iOS设备上只读消耗远程JSON数据的所有必要步骤.这意味着获取远程JSON数据,存储到iOS设备上的本地缓存以供脱机使用,刷新缓存,解析JSON数据.我认为现在所有移动应用都是非常普遍的要求.
我知道可以手动下载远程JSON文件,将其存储到iOS设备上的本地数据库或文件中,当网络不可用时从本地存储中获取它,否则从网上下载.我现在手动完成.:)但是希望通过使用框架/库可以做的许多步骤,不是吗?
所以我尝试了几乎所有我需要的HanekeSwift框架,但它只缓存远程JSON(和图像),但不刷新缓存!这对我没用.我也知道存在Alamofire和SwiftyJSON,但我对它们没有任何经验.
你有任何经验如何做到这一点?
摘要

我有一个测试应用程序设置,即使用户在下载过程中切换应用程序,它也能成功从网络下载内容.太好了,现在我有后台下载了.现在我想添加缓存.没有必要让我多次下载图像,b/c系统设计,给定一个图像URL我可以告诉你该URL后面的内容永远不会改变.所以,现在我想使用Apple内置的内存/磁盘缓存来缓存下载的结果,我已经阅读了很多(而不是我在NSCachesDirectory中手动保存文件,然后在创建之前检查文件)请求,ick).在尝试得到缓存在此工作的代码顶部的工作,我添加以下代码:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Set app-wide shared cache (first number is megabyte value)
[NSURLCache setSharedURLCache:[[NSURLCache alloc] initWithMemoryCapacity:60 * 1024 * 1024
diskCapacity:200 * 1024 * 1024
diskPath:nil]];
return YES;
}
Run Code Online (Sandbox Code Playgroud)
当我创建会话时,我添加了两行NEW(URLCache和requestCachePolicy).
// Helper method to get a single session object
- (NSURLSession *)backgroundSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
configuration.URLCache = [NSURLCache sharedURLCache]; // NEW LINE …Run Code Online (Sandbox Code Playgroud) iphone nsurlcache ios nsurlsession nsurlsessionconfiguration
这是我需要清除缓存并对URL进行新调用时调用的示例函数
- (void)clearDataFromNSURLCache:(NSString *)urlString
{
NSURL *requestUrl = [NSURL URLWithString:urlString];
NSURLRequest *dataUrlRequest = [NSURLRequest requestWithURL: requestUrl];
NSURLCache * cache =[NSURLCache sharedURLCache];
NSCachedURLResponse* cacheResponse =[cache cachedResponseForRequest:dataUrlRequest];
if (cacheResponse) {
NSString* dataStr = [NSString stringWithUTF8String:[[cacheResponse data] bytes]];
NSLog(@"data str r= %@",dataStr);
NSLog(@"url str r= %@",[[[cacheResponse response] URL] absoluteString]);
[cache storeCachedResponse:nil forRequest:dataUrlRequest];
[NSURLCache setSharedURLCache:cache];
}
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:dataUrlRequest];
//Check if the respnase data has been removed/deleted from cache
NSURLRequest *finalRequestUrlRequest = [NSURLRequest requestWithURL:requestUrl];
NSURLCache * finalCache =[NSURLCache sharedURLCache];
NSCachedURLResponse* finalcacheResponse =[finalCache cachedResponseForRequest:finalRequestUrlRequest];
if …Run Code Online (Sandbox Code Playgroud) ios ×3
caching ×2
nsurlcache ×2
alamofire ×1
http ×1
ios8 ×1
iphone ×1
nsurlsession ×1
objective-c ×1
swift ×1