在NSURLProtocol中使用NSURLSession [英] Using NSURLSession inside NSURLProtocol

查看:237
本文介绍了在NSURLProtocol中使用NSURLSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用NSURLSession为http://和https://连接创建一个透明的NSURLProtocol.但是,目前,即使正在运行完成处理程序,带有应用程序(UIWebView)的URL请求也变回空白.有人有什么想法吗?代码如下:

I'm trying to create a transparent NSURLProtocol for http:// and https:// connections using NSURLSession. However at the moment, even though the completion handler is being run, URL requests with the app (UIWebView) are coming back blank. Does anybody have any ideas? Code is below:

#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

推荐答案

您的代码正在使用NSURLConnection委托将数据传递回调用方,例如connectionDidFinishLoading:.

Your code is using NSURLConnection delegates to pass data back to the caller, e.g. connectionDidFinishLoading:.

要解决此问题:

  • NSURLSession委托方法替换它们.
  • 创建并保留一个自定义会话,其委托是您的协议类实例;共享会话没有委托,因此不会调用类的委托方法.
  • 删除回调块,以便正确完成请求的委托方法.
  • Replace these with NSURLSession delegate methods.
  • Create and retain a custom session whose delegate is your protocol class instance; the shared session doesn't have a delegate, so it won't call your class's delegate methods.
  • Remove the callback block so that the delegate method for request completion will be called correctly.

这篇关于在NSURLProtocol中使用NSURLSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆