【问题标题】:NSURL Connection cache data for offine appNSURLConnection 为离线应用缓存数据
【发布时间】:2013-10-07 02:39:00
【问题描述】:

我必须为 i iphone 开发一个应用程序,它可以以两种方式工作,一种是在线,另一种是离线。当有互联网时,它应该显示来自网络的数据,但当没有网络时,它需要显示缓存的数据.我正在使用 nsurl 连接从服务器获取数据。我的代码如下

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:strUrl]
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];

NSURLConnection *conn = [NSURLConnection connectionWithRequest:request
                                                      delegate:self];
[conn start];

还有没有被调用的委托

-(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse: 
(NSCachedURLResponse *)cachedResponse
 {
return cachedResponse;
 } 

谁能指导我如何在ios的NSURLConnection中获取存储在缓存中的数据。提前谢谢。:)

【问题讨论】:

  • stackoverflow.com/questions/16454719/… 这是一个类似的问题
  • 我认为回答你的问题已经足够清楚了:)
  • @HubertWang 我认为这与缓存无关,而与 NSURLConnection 的工作原理有关..
  • nsurlconnection 会一点一点地获取数据,然后您管理一个 NSData 对象来接收数据。可以看到connectionDidFinishLoading,数据完成并存储到指定的路径。
  • 但是数据存储在缓存中我只需要访问它..@HubertWang

标签: iphone ios caching nsurlconnection


【解决方案1】:

抱歉,您需要对此进行一些研究:) 希望这会帮助你 我尝试下载图像,即使在离线状态下我也会得到它。 只是通过这可能对你有帮助:)

在应用委托中设置创建缓存

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
  // Override point for customization after application launch.
  self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
  //need to add this
  NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024
                                                     diskCapacity:20 * 1024 * 1024
                                                         diskPath:nil];
  [NSURLCache setSharedURLCache:URLCache];
  // set sharedcache

  self.window.rootViewController = self.viewController;
  [self.window makeKeyAndVisible];
  return YES;
}  

//在你的下载视图控制器中

    #import "ViewController.h"
    @interface ViewController ()<NSURLConnectionDelegate> // confirms to this delegate
     {
         NSMutableData *imagData;
     }

     @end

     @implementation ViewController

     - (void)viewDidLoad
      {
         [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

         NSURL *url = [NSURL           URLWithString:@"http://static.adzerk.net/Advertisers/d9a919813dac42adbd0e3106bc19bc04.png"];
         NSURLRequest *Req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];

        NSURLConnection *conn = [NSURLConnection connectionWithRequest:Req delegate:self];
        if(conn == nil)
        {
           conn = nil;
           [conn cancel];
        }

   }


   - (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
    {

       if(imagData == nil)
       {
          imagData = [[NSMutableData alloc]init];
       }

     //    NSURLResponse *resp = [[NSURLResponse alloc]initWithURL:[NSURL        URLWithString:@"http://static.adzerk.net/Advertisers/d9a919813dac42adbd0e3106bc19bc04.png"]    MIMEType:@"" expectedContentLength:50 textEncodingName:@"image"];
    //    NSLog(@"%@",connection.description);
    //    NSLog(@"%@",resp.description);
    //    
     //    NSCachedURLResponse *chacheResp = [[NSCachedURLResponse alloc]initWithResponse:resp data:data];
    //    

     [imagData  appendData:data];
      UIImage *aimage=[[UIImage alloc]initWithData:imagData];
      self.aview.image = aimage;
    } 


  -(NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
   {
       NSMutableDictionary *userInfo = [[cachedResponse userInfo] mutableCopy];
       NSMutableData *mutData = [[cachedResponse data] mutableCopy];
       NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;


       return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                data:mutData
                                            userInfo:userInfo
                                       storagePolicy:storagePolicy];

   }

   - (void)connectionDidFinishLoading:(NSURLConnection *)connection
   {
       connection = nil;
       [connection cancel];
   }

还可以通过 AdamG 提供的链接

【讨论】:

    【解决方案2】:

    你需要确保在applicationDidFinishLaunching:分配缓存

    这是您需要执行此操作的代码:

    NSURLCache *URLCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 
                                                       diskCapacity:20 * 1024 * 1024 
                                                           diskPath:nil];
    [NSURLCache setSharedURLCache:URLCache];
    

    而且缓存代码也应该看起来不同:

      - (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
                  willCacheResponse:(NSCachedURLResponse *)cachedResponse
     {
        NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];
        NSMutableData *mutableData = [[cachedResponse data] mutableCopy];
        NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;
    
        // ...
    
        return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response]
                                                    data:mutableData
                                                userInfo:mutableUserInfo
                                           storagePolicy:storagePolicy];
     }
    

    有关更多信息,请参阅 http://www.nshipster.com/nsurlcache/,但这应该可以解决您的问题。

    【讨论】:

    • 代表仍然没有接到电话...:(
    • 这可能很愚蠢,但是从文档中复制并粘贴方法,有时这对我来说已经解决了这类问题,因为某种拼写错误导致了问题。
    • 还要确保你已经在@interface 之后声明你的类是一个使用 的 NSURLConnectionDelegate
    • NSURLConnection 是否调用了其他委托方法?
    • .其他代表被正确调用除了- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse {
    猜你喜欢
    • 2023-03-10
    • 1970-01-01
    • 2019-04-08
    • 2013-06-14
    • 1970-01-01
    • 2013-01-23
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多