1

我必须为 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中获取存储在缓存中的数据。在此先感谢。:)

4

2 回答 2

1

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

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

  - (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 提供的链接

于 2013-10-01T05:57:26.597 回答
1

您需要确保在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/但这可能会解决您的问题。

于 2013-10-01T04:46:35.703 回答