Drupal News

Drupal 8 and iOS: Use Caching with NSURLRequest

Planet Drupal - Sat, 05/07/2014 - 6:45am
Use Caching with NSURLRequest

I am Vivek Pandya and I am working on Google Summer of Code 2014 project to build an iOS application for Drupal 8 site. In this article I am sharing my experience about caching retrieved data from Durpal 8 REST web service with in iOS7 application.

While writing iOS application that loads data(JSON) like a list of articles it is better to use cache mechanism provided by NSURLSession api. An NSURLRequest instance specifies how local cache is used by setting NSURLRequestCachePolicy values: with NSURLRequestProtocolCachePolicy, NSURLRequestReloadIgnoringCacheData, NSURLRequestReturnCacheDataElseLoad, NSURLRequestReturnCacheDataDontLoad etc.

The default cache policy for an NSURLRequest is NSURLRequestUseProtocolCachePolicy. While working with REST endpoint HTTP is default protocol so when NSCachedURLResponse does not exist for the request the NSURLSession will fetch data for that request.

If cached response exist than NSURLSession api will make HEAD request to the resource and check for cached data's validity by examining various response header like “Last-Modified” , “Cache-Control” etc. And if it finds data to be stale one it will load the data again otherwise returns cached data.

But, before using this cache mechanism at iOS side we have to make our Drupal site pages cacheable to do so navigate to “admin/config/development/performance” and set time limit value for page cache. Save the configuration. Now to verify whether Drupal has really enabled cache for pages or note try HEAD request with any REST api client like Postman, in response header you should be able to see “Cache-Control : max-age=<seconds>” here seconds should be same as you specified in configuration. See the picture below to get more clarity.

Now while creating request object with iOS SDK set it's caching policy to NSURLRequestProtocolCachePolicy. Now run the code , first time it will take normal time to load the data but next time onwards it will only reload the data if it has been changed or max-age value has expired.

For more details please refer to URLLoading system guide by Apple.

 

Tags:
Categories: Drupal News

Theme by Danetsoft and Danang Probo Sayekti inspired by Maksimer