Created
June 8, 2012 18:45
-
-
Save krisselden/2897538 to your computer and use it in GitHub Desktop.
handle a specific http + domain as a local resource
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "YappPhoneGapLocalURLProtocol.h" | |
#ifdef PHONEGAP_FRAMEWORK | |
#import <PhoneGap/PhoneGapDelegate.h> | |
#else | |
#import "PhoneGapDelegate.h" | |
#endif | |
@interface YappPhoneGapLocalURLProtocol () <NSURLConnectionDelegate, NSURLConnectionDataDelegate> | |
@property (nonatomic, retain) NSURLConnection *connection; | |
@end | |
@implementation YappPhoneGapLocalURLProtocol | |
@synthesize connection = connection_; | |
-(void)dealloc | |
{ | |
[self.connection cancel]; | |
self.connection = nil; | |
[super dealloc]; | |
} | |
+ (BOOL)canInitWithRequest:(NSURLRequest *)request | |
{ | |
NSURL *url = [request URL]; | |
if ([[url scheme] isEqualToString:@"http"] && | |
[[url host] isEqualToString:@"phonegap.yapp.us"]) { | |
return YES; | |
} | |
return NO; | |
} | |
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request | |
{ | |
return request; | |
} | |
- (void)startLoading | |
{ | |
NSLog(@"YappPhoneGapLocalURLProtocol startLoading %@", [self.request URL]); | |
NSString *path = [[self.request URL] path]; | |
NSString *resourcePath = [PhoneGapDelegate pathForResource:path]; | |
NSURL *resourceURL = [NSURL fileURLWithPath:resourcePath]; | |
NSURLRequest *resouceRequest = [NSURLRequest requestWithURL:resourceURL]; | |
self.connection = [NSURLConnection connectionWithRequest:resouceRequest delegate:self]; | |
} | |
- (void)stopLoading | |
{ | |
[self.connection cancel]; | |
} | |
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse | |
{ | |
return cachedResponse; | |
} | |
- (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response | |
{ | |
return request; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response | |
{ | |
[self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; | |
} | |
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data | |
{ | |
[self.client URLProtocol:self didLoadData:data]; | |
} | |
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error | |
{ | |
[self.client URLProtocol:self didFailWithError:error]; | |
self.connection = nil; | |
} | |
- (void)connectionDidFinishLoading:(NSURLConnection *)connection | |
{ | |
[self.client URLProtocolDidFinishLoading:self]; | |
self.connection = nil; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment