ios - 覆盖 UIWebView 用户代理 - 但不适用于 Facebook SDK

标签 ios facebook uiwebview

我正在按照this other question中的说明为我的应用程序中的 WebView 设置自定义UserAgent 。具体来说,我正在设置

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

在应用程序启动时。 (仅为 UIWebView 使用的 NSMutableURLRequest 设置适当的 header - UserAgent、User-Agent、User_Agent - 不起作用。)

这会导致我的嵌入式 Web View 使用正确的用户代理。然而,它也破坏了 Facebook SDK 用于对话框的嵌入式 Web View - 例如,在我发布到我的墙上后,FB 对话框 Web View 的内容被替换为类似于 窗口的文本 .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"];,但随后我的 webview 无法正常显示用户代理。

当然,肯定有人之前在具有非 Facebook 嵌入 Web View 的应用程序中使用过 Facebook SDK。我缺少什么?我已经对此进行了多次研究,每一次似乎都几乎但并非完全解决了所有问题。

最佳答案

我最终不得不通过实现 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

请注意,在发出要应用该协议(protocol)的任何 Web 请求之前,必须使用 [NSURLProtocol registerClass:[MyProtocol class]]; 注册该协议(protocol) - 例如,在 applicationDidFinishLaunchingWithOptions 中:

关于ios - 覆盖 UIWebView 用户代理 - 但不适用于 Facebook SDK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16158970/

相关文章:

ios - 无法从 UIWebView 获取要在 HTML 中呈现的 css 文件样式

ios - AVPlayer 返回 nan 视频

ios - 使用 UICollectionViewFlowLayout/UICollectionViewLayout 子类,不会在正确的时间调用 CellForItemAtIndexPath

ios - Paypal SDK 集成问题

ios - 为 Phonegap Build 应用程序添加不带 Xcode 的 facebook iOS SDK

ios - 在 UIViewController 之间传递数据

ios - 如何在转换前强制加载 UIWebView

ios - 将 UiBarButtonItem 上的 UIImage 从标识符更新为图像

iphone - iOS Facebook SDK 3.1 登录时添加权限

iphone - 如何在 iPhone 中以编程方式使用 fbrequest 在 Facebook 好友墙上发帖?