0

我正在按照其他问题中的说明为我的应用程序中的 webviews 设置自定义 UserAgent 。具体来说,我正在设置

NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:@"MyApp/MyLongVersionInfoString", @"UserAgent", nil];
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];

在应用启动时。(只需为 UIWebView 使用的 NSMutableURLRequest 设置适当的标头 - UserAgent、User-Agent、User_Agent - 不起作用。)

这会导致我的嵌入式 webviews 使用正确的用户代理。但是,它也破坏了 Facebook SDK 用于对话框的嵌入式 webviews - 例如,在我发布到我的墙上后,FB 对话框 webview 的内容被替换为类似的文本window.location.href="fbconnect:\/\/success?post_id=100002469633196_43677789308119...,并且 webview 不会像往常那样关闭(用户必须手动关闭它)。这只发生在我设置了自定义用户代理时。

我想我可以通过在 Facebook 调用之前取消设置用户代理并在之后重置它来规避这个问题,但似乎我无法取消设置默认默认值;我尝试在每个 Facebook 调用之前调用[[NSUserDefaults standardUserDefaults] removeObjectForKey:@"UserAgent"][[NSUserDefaults standardUserDefaults] removePersistentDomainForName:NSRegistrationDomain]在调用的结果处理程序中再次设置它们,但我仍然看到相同的不当行为。

我尝试将我的初始设置切换为[[NSUserDefaults standardUserDefaults] setObject:newUA forKey:@"UserAgent"];,但是我的webviews 没有选择用户代理。

可以肯定的是,之前有人在具有非 Facebook 嵌入式 Web 视图的应用程序中使用过 Facebook SDK。我错过了什么?我已经为此进行了几轮,每一次似乎都几乎但不是完全解决了所有问题。

4

1 回答 1

1

我最终不得不通过实现一个 NSURLProtocol 子类来做到这一点。虽然我的实现很混乱,但我在下面包含了一个经过清理的版本,因为我很惊讶无法在 StackOverflow 上找到一个示例。

#import <Foundation/Foundation.h>

@interface MyProtocol : NSURLProtocol {
    NSURLConnection *connection;
}

@property (nonatomic, retain) NSURLConnection *connection;

@end

@implementation MyProtocol

@synthesize connection;

#pragma mark -
#pragma mark custom methods

+ (NSString *)myUA {
    return [[NSUserDefaults standardUserDefaults] stringForKey:@"MyCustomUserAgent"];
}
+ (BOOL)canInitWithRequest:(NSURLRequest *)request
{
    NSString *scheme = [request.URL.scheme stringByAppendingString:@"://"];
    NSString *baseRequestString = [[[request.URL absoluteString] stringByReplacingOccurrencesOfString:request.URL.path withString:@""]
                                   stringByReplacingOccurrencesOfString:scheme withString:@""];
    if (request.URL.query != nil) {
        NSString *query = [@"?" stringByAppendingString:request.URL.query];
        baseRequestString = [baseRequestString stringByReplacingOccurrencesOfString:query withString:@""];
    }

    BOOL shouldIntercept = [baseRequestString isEqualToString:myWebHost];
    BOOL alreadyIntercepted = [[NSURLProtocol propertyForKey:@"UserAgent" inRequest:request] isEqualToString:[self myUA]];
    return shouldIntercept && !alreadyIntercepted;
}

+ (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request
{
    return request;
}

- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)cachedResponse client:(id<NSURLProtocolClient>)client
{
    NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:request.URL
                                                       cachePolicy:request.cachePolicy
                                                   timeoutInterval:request.timeoutInterval];
    [mutableRequest setAllHTTPHeaderFields:[request allHTTPHeaderFields]];
    [mutableRequest setHTTPMethod:[request HTTPMethod]];
    if ([request HTTPBody] != nil)
        [mutableRequest setHTTPBody:[request HTTPBody]];
    if ([request HTTPBodyStream] != nil)
        [mutableRequest setHTTPBodyStream:[request HTTPBodyStream]];
    [NSURLProtocol setProperty:[[self class] myUA] forKey:@"UserAgent" inRequest:mutableRequest];
    [mutableRequest setValue:[[self class] myUA] forHTTPHeaderField:@"User-Agent"];
    [mutableRequest setValue:[[self class] myUA] forHTTPHeaderField:@"User_Agent"];

    self = [super initWithRequest:mutableRequest cachedResponse:cachedResponse client:client];
    return self;
}

- (void) dealloc
{
    [connection release];
}

#pragma mark -
#pragma mark boilerplate NSURLProtocol subclass requirements

- (void) startLoading
{
    self.connection = [[NSURLConnection connectionWithRequest:[self request] delegate:self] retain];
}

- (void)stopLoading
{
    [self.connection cancel];
}

- (void)connection:(NSURLConnection*)conn didReceiveResponse:(NSURLResponse*)response
{
    [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:[[self request] cachePolicy]];
}

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    [[self client] URLProtocol:self didLoadData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)conn
{
    [[self client] URLProtocolDidFinishLoading:self];
}

- (NSURLRequest*)connection:(NSURLConnection*)connection willSendRequest:(NSURLRequest*)theRequest redirectResponse:(NSURLResponse*)redirectResponse
{
    return theRequest;
}

- (void)connection:(NSURLConnection*)conn didFailWithError:(NSError*)error
{
    [[self client] URLProtocol:self didFailWithError:error];
}

@end

请注意,[NSURLProtocol registerClass:[MyProtocol class]];在您发出任何您希望它应用的 Web 请求之前,必须先注册该协议 - 例如,在applicationDidFinishLaunchingWithOptions:.

于 2013-05-09T02:41:26.877 回答