开发者

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

开发者 https://www.devze.com 2023-02-10 23:45 出处:网络
There are a lot of threads about using UIWebView with caches and/or cookies, but they all seem to relate to remote URLs.

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.


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


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号