如何在iOS应用程序中修改NSURLRequest中的cookie

时间:2012-02-17 00:34:09

标签: objective-c ios

您好我需要修改cookie,但我正在iOS中开发,有人知道如何更改它。也许在UIWebViewDelegate中使用webView:shouldStartLoadWithRequest:navigationType:??

1 个答案:

答案 0 :(得分:4)

因为WebKit.framework不适用于IOS,最好的方法是将事件用于UIWebView shouldStartLoadWithRequest和webViewDidFinishLoad,在那里我使用NSHTTPCookieStorage类作为cookie并在那里修改它如下

NSHTTPCookieStorage *sharedHTTPCookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *cookies = [sharedHTTPCookieStorage cookiesForURL:[NSURL URLWithString:self.webView.request.URL.absoluteString]];
NSEnumerator *enumerator = [cookies objectEnumerator];
NSHTTPCookie *cookie;
while (cookie = [enumerator nextObject])
{
    if ([[cookie name] isEqualToString:key]) 
    {
        NSString *actcookie = [cookie value];
        NSMutableString *newcookiestring = [NSMutableString stringWithFormat:@"%@changes",actcookie];
        NSMutableDictionary *propscook = [[NSMutableDictionary alloc] initWithDictionary: [cookie properties]];
        [propscook setObject:newcookiestring forKey:NSHTTPCookieValue];
        NSHTTPCookie *newcookie = [NSHTTPCookie cookieWithProperties:propscook];

        [sharedHTTPCookieStorage setCookie:newcookie];

        return [cookie value];
    }
}
return nil;