2016-02-25 43 views
0

我想爲使用NSURLSession的http://和https://連接創建一個透明的NSURLProtocol。然而,目前,即使完成處理程序正在運行,使用應用程序(UIWebView)的URL請求仍然空白。有人有任何想法嗎?代碼如下:在NSURLProtocol裏面使用NSURLSession

#import "MyURLProtocol.h" 

// AppDelegate 
#import "AppDelegate.h" 

static NSString * const MyURLProtocolHandledKey = @"MyURLProtocolHandledKey"; 

@interface MyURLProtocol() <NSURLConnectionDelegate,NSURLSessionDelegate> 

@property (nonatomic, strong) NSURLConnection *connection; 
@property (nonatomic, strong) NSMutableData *mutableData; 
@property (nonatomic, strong) NSURLResponse *response; 

@end 

@implementation MyURLProtocol 

+(BOOL)canInitWithRequest:(NSURLRequest*)request 
{ 
    if ([NSURLProtocol propertyForKey:MyURLProtocolHandledKey inRequest:request]) 
     return NO; 
    NSString *scheme = request.URL.scheme.lowercaseString; 
    return [scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]; 
} 

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

-(void)startLoading 
{  
    NSMutableURLRequest *newRequest = [self.request mutableCopy]; 
    [NSURLProtocol setProperty:@YES forKey:@"MyURLProtocolHandledKey" inRequest:newRequest]; 

    NSURLRequest *request = newRequest; 

    NSURLSession *session = [NSURLSession sharedSession]; 
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request 
              completionHandler: 
            ^(NSData *data, NSURLResponse *response, NSError *error) { 
             if (error != nil) { 
              NSLog(@"There was an error"); 
             } 
             NSLog(@"Completiio handler ran"); 
             self.mutableData = [NSMutableData dataWithData:data]; 
             self.response = response; 
            }]; 

    [task resume]; 
} 

- (void) stopLoading { 

    [self.connection cancel]; 
    self.mutableData = nil; 
} 

// Delegate stuff 

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

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

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

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

@end 

回答

1

您的代碼正在使用NSURLConnection代表將數據傳回給調用者,例如, connectionDidFinishLoading:

要解決這個問題:

  • NSURLSession委託方法替換這些。
  • 創建並保留一個自定義會話,其委託是您的協議類實例;共享會話沒有委託,所以它不會調用你的類的委託方法。
  • 刪除回調塊,以便正確調用請求完成的委託方法。