Matt
Matt

Reputation: 4570

Cookies don't work in UIWebView displaying "local content"

There are a lot of threads about using UIWebView with caches and/or cookies, but they all seem to relate to remote URLs.

I cannot get cookies to work when "displaying local content" (as the iPhone docs call it).

For example, if I load a plain old HTML file from my bundle resource:

     - (void) viewDidLoad {
        [super viewDidLoad];

        NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
        NSURL* url = [NSURL fileURLWithPath:path];
        NSData* data = [NSData dataWithContentsOfFile:path];
        [web loadData:data MIMEType:@"text/html" textEncodingName:@"us-ascii" baseURL:url];
    }

then:

    - (void) webViewDidFinishLoad:(UIWebView*)webView {
        NSString* result = [web stringByEvaluatingJavaScriptFromString:
                            @"try{document.cookie='name=value';''+document.cookie;}catch(e){''+e}"];
        NSLog(@"Result = '%@'", result);
    }

results in:

    Result = ''

Setting the URL to be the actual filename rather than the directory prevents getting: Result = 'Error: SECURITY_ERR: DOM Exception 18', but the cookies do not seem to persist.

Upvotes: 1

Views: 3654

Answers (3)

Jan
Jan

Reputation: 1612

If your aim is to store data in the UIWebView you can also use window.localStorage. It is a hashtable in which you can store max. 5MB of string data.

e.g.

window.localStorage['highscore_level_1']='12000';

alert(window.localStorage['highscore_level_1']);

I've used this succesfully to implement a highscore table in an UIWebView based iPhone App.

Upvotes: 1

Matt
Matt

Reputation: 4570

I have found a satisfactory work-around. By specifying a real URL, such as http://localhost/..., and then intercepting the loading, by subclassing the NSURLCache class, in order to fetch actual local content.

- (NSCachedURLResponse*) cachedResponseForRequest:(NSURLRequest *)request {
    NSString* path = [[request URL] path];

    NSData* data = [... get content of local file ...];

    NSURLResponse *response = [[NSURLResponse alloc] 
                               initWithURL:[request URL]
                               MIMEType:[self mimeTypeForPath:path]
                               expectedContentLength:[data length]
                               textEncodingName:nil];

    NSCachedURLResponse* cachedResponse = [[NSCachedURLResponse alloc] 
                                           initWithResponse:response 
                                           data:data];
    [response release];

    return [cachedResponse autorelease];
}

Upvotes: 3

Brirony
Brirony

Reputation: 29

Well you could check out NSHTTPCookieStorage class reference. But If you're using the webView for local content, what is the purpose of using cookies? Why not just save that info some other way on your app?

Upvotes: 2

Related Questions