Skip to content

Instantly share code, notes, and snippets.

@wkiefer
Created April 12, 2012 11:00
Show Gist options
  • Save wkiefer/2366514 to your computer and use it in GitHub Desktop.
Save wkiefer/2366514 to your computer and use it in GitHub Desktop.
Notes on using NSURLProtocol
// The basics:
// - Write your own NSURLProtocol subclass and register it.
// - Override the 5 required methods
// - Kick off download or cache fetch during |startLoading|
// - Update self.client with progress/completion/failure notifications.
// UIWebView will download requests concurrently via NSURLProtocol.
// If you use the typical NSURLCache hook to download content, you're
// stuck with serial downloads.
// Register once. +load is a good time.
[NSURLProtocol registerClass:[MyURLProtocol class]];
// iOS will call this selector on all registered URL
// protocols in reverse-registration order.
// Here, decide whether it's a request you want to handle.
+ (BOOL)canInitWithRequest:(NSURLRequest *)request;
// Also implement:
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request;
+ (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a
toRequest:(NSURLRequest *)b;
- (void)startLoading {
NSData *data = // Get cached data
if (data) {
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
} else {
// Create our GTMHTTPFetcher *fetcher_
[fetcher_ beginFetchWithCompletionHandler:^(/*...*/) {
// Grab download off disk, or cache, etc... then:
[[self client] URLProtocol:self didLoadData:data];
[[self client] URLProtocolDidFinishLoading:self];
}];
}
}
// Use [self client] NSURLProtocolClient methods to update download state/progress.
@UlliH
Copy link

UlliH commented Jan 5, 2013

Hi,

I´m a absolute Newbe and have no chance.

I'll save the data in a DB. Can you tell me, how to handle this?

[fetcher_ beginFetchWithCompletionHandler:^(/.../) {

// Grab download off disk, or cache, etc... then:

TIA, UlliH

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment