1

I have to develop a application for i iphone which can work in two way one is on line other is offline.When there is internet it should show the data from the network but when there is no network it needed to show cached data.I am using nsurl connection for getting data from server.My code is following

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

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

also the delegate which is not getting called as well

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

can anyone please guide me how to get data stored in cache in NSURLConnection in ios..Thanks in advance.:)

Sishu
  • 1,510
  • 1
  • 21
  • 48
  • http://stackoverflow.com/questions/16454719/how-download-file-with-nsurlconnection-in-storyboard here is a similar question – Hubert Wang Oct 01 '13 at 04:14
  • I think it is clear enough to answer you question :) – Hubert Wang Oct 01 '13 at 04:15
  • @HubertWang i think it is not about the cache,only about how NSURLConnection works.. – Sishu Oct 01 '13 at 04:17
  • The nsurlconnection get you data bit by bit, and you manage an NSData object to receive the data. You can see connectionDidFinishLoading, the data is completed and being stored to a path specified. – Hubert Wang Oct 01 '13 at 04:20
  • but data is stord in cache i only need to access it ..@HubertWang – Sishu Oct 01 '13 at 04:22
  • @HubertWang pls help me in dealing with cache ,,:) – Sishu Oct 01 '13 at 04:24
  • Oh, I think I know what you mean. Hmm, I am not sure if the cache is used to download file, maybe they are just fragment of data. Maybe you can try other third party library such as ASIHTTP? It can specify download path directly and are able to resume download(if server supports) – Hubert Wang Oct 01 '13 at 04:27
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38382/discussion-between-ioskills-and-hubert-wang) – Sishu Oct 01 '13 at 04:29

2 Answers2

1

You need to make sure to allocate the cache in applicationDidFinishLaunching:

This is the code you need to do that:

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

And the caching code should also look different:

  - (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];
 }

For more see http://www.nshipster.com/nsurlcache/ but that should probably fix your problem.

AdamG
  • 3,718
  • 2
  • 18
  • 28
  • delegate not getting call still...:( – Sishu Oct 01 '13 at 05:29
  • This might be silly but copy and paste the method from the documentation, sometimes this has fixed this sort of problem for me because some sort of mispelling has caused an issue. – AdamG Oct 01 '13 at 05:32
  • Also make sure you have declared after the @interface that your class is an NSURLConnectionDelegate using <> – AdamG Oct 01 '13 at 05:33
  • Are your other delegate methods getting called for NSURLConnection? – AdamG Oct 01 '13 at 05:34
  • .other delegates are getting called properly except- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { – Sishu Oct 01 '13 at 05:36
  • Are you sure your server is configured correctly with the correct headers? – AdamG Oct 01 '13 at 05:38
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/38385/discussion-between-ioskills-and-adamg) – Sishu Oct 01 '13 at 05:40
1

Sorry for delay u need to do some research on this :) hope this will helps u i tried by downloading the image i will get it even in the offline. just go throught this may be helps u :)

in app delegate set the create cache

  - (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;
}  

//in your downloading view controller

    #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];
   }

and also go through link provided by AdamG

Shankar BS
  • 8,394
  • 6
  • 41
  • 53