我们正在为iOS构建一个浏览器。为了实现我们自己的缓存方案并执行用户代理欺骗,我们决定使用自定义的NSURLProtocol子类进行实验。well...the的问题是,导航到特定的站点(msn.com是最糟糕的)将导致整个应用程序的UI冻结15秒。显然,有东西阻塞了主线程,但它不在我们的代码中。
此问题仅在UIWebView和自定义协议的组合中出现。如果我们交换一个WKWebView (由于各种原因我们不能使用),那么问题就会消失。类似地,如果我们不注册该协议,使其从未被使用过,问题就会消失。
协议做什么似乎也无关紧要;我们编写了一个基本的虚拟协议,它只做转发响应(post的底部)。我们把这个协议放到了一个没有任何其他代码的普通测试浏览器中-同样的结果。我们还尝试使用其他人的(RNCachingURLProtocol),并观察到同样的结果。这两个组件与某些页面的简单组合似乎会导致冻结。我不知道如何解决(甚至是调查)这个问题,我会非常感谢任何的指导和建议。谢谢!
import UIKit
private let KEY_REQUEST_HANDLED = "REQUEST_HANDLED"
final class CustomURLProtocol: NSURLProtocol {
var connection: NSURLConnection!
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
return NSURLProtocol.propertyForKey(KEY_REQUEST_HANDLED, inRequest: request) == nil
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override class func requestIsCacheEquivalent(aRequest: NSURLRequest, toRequest bRequest: NSURLRequest) -> Bool {
return super.requestIsCacheEquivalent(aRequest, toRequest:bRequest)
}
override func startLoading() {
var newRequest = self.request.mutableCopy() as! NSMutableURLRequest
NSURLProtocol.setProperty(true, forKey: KEY_REQUEST_HANDLED, inRequest: newRequest)
self.connection = NSURLConnection(request: newRequest, delegate: self)
}
override func stopLoading() {
connection?.cancel()
connection = nil
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
self.client!.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: .NotAllowed)
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
self.client!.URLProtocol(self, didLoadData: data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
self.client!.URLProtocolDidFinishLoading(self)
}
func connection(connection: NSURLConnection!, didFailWithError error: NSError!) {
self.client!.URLProtocol(self, didFailWithError: error)
}
}发布于 2016-03-08 01:19:11
我刚刚用msn.com检查了msn.com的行为,发现在某种程度上,startLoading方法是以WebCoreSynchronousLoaderRunLoopMode模式调用的。这会导致主线程阻塞。
纵观CustomHTTPProtocol苹果示例代码,我发现了描述这个问题的注释。Fix将以下一种方式实现:
@interface CustomHTTPProtocol () <NSURLSessionDataDelegate>
@property (atomic, strong, readwrite) NSThread * clientThread; ///< The thread on which we should call the client.
/*! The run loop modes in which to call the client.
* \details The concurrency control here is complex. It's set up on the client
* thread in -startLoading and then never modified. It is, however, read by code
* running on other threads (specifically the main thread), so we deallocate it in
* -dealloc rather than in -stopLoading. We can be sure that it's not read before
* it's set up because the main thread code that reads it can only be called after
* -startLoading has started the connection running.
*/
@property (atomic, copy, readwrite) NSArray * modes;
- (void)startLoading
{
NSMutableArray *calculatedModes;
NSString *currentMode;
// At this point we kick off the process of loading the URL via NSURLSession.
// The thread that calls this method becomes the client thread.
assert(self.clientThread == nil); // you can't call -startLoading twice
// Calculate our effective run loop modes. In some circumstances (yes I'm looking at
// you UIWebView!) we can be called from a non-standard thread which then runs a
// non-standard run loop mode waiting for the request to finish. We detect this
// non-standard mode and add it to the list of run loop modes we use when scheduling
// our callbacks. Exciting huh?
//
// For debugging purposes the non-standard mode is "WebCoreSynchronousLoaderRunLoopMode"
// but it's better not to hard-code that here.
assert(self.modes == nil);
calculatedModes = [NSMutableArray array];
[calculatedModes addObject:NSDefaultRunLoopMode];
currentMode = [[NSRunLoop currentRunLoop] currentMode];
if ( (currentMode != nil) && ! [currentMode isEqual:NSDefaultRunLoopMode] ) {
[calculatedModes addObject:currentMode];
}
self.modes = calculatedModes;
assert([self.modes count] > 0);
// Create new request that's a clone of the request we were initialised with,
// except that it has our 'recursive request flag' property set on it.
// ...
// Latch the thread we were called on, primarily for debugging purposes.
self.clientThread = [NSThread currentThread];
// Once everything is ready to go, create a data task with the new request.
self.task = [[[self class] sharedDemux] dataTaskWithRequest:recursiveRequest delegate:self modes:self.modes];
assert(self.task != nil);
[self.task resume];
}一些苹果的工程师有很好的幽默感。
令人兴奋是吧?
详情请参见全苹果样品。
这个问题在WKWebView中是不可复制的,因为NSURLProtocol不能使用它。详情请参见下一个问题。
https://stackoverflow.com/questions/31327785
复制相似问题