UIWebView Delegate获取MIME类型

Pas*_*Kit 5 objective-c uiwebview nsurlconnection ios6

UIWebView不会自动支持处理Passbook .pkpass文件.

在本技术说明中,Apple建议通过UIWebViewDelegate方法实现检查,以嗅探MIME类型并相应地处理它.

要使用UIWebView添加传递,请实现相应的UIWebViewDelegate方法,以确定视图何时加载MIME类型为application/vnd.apple.pkpass的数据

但是,我在UIWebView委托协议参考中找不到能够提供MIME类型的任何内容.

我可以使用NSURLConnection委托直接下载和处理文件,没有任何问题,但我希望实现的是,如果用户在UIWebView中浏览时单击"添加到存折"按钮,则可以正确处理传递.由于我不知道链接,并且许多提供商没有使用.pkpass扩展名后缀,因此遵循Apple的检查MIME类型的建议似乎是最好的方法.

我尝试添加以下内容

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)newRequest 
                                                 navigationType:(UIWebViewNavigationType)navigationType 
{

   NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[newRequest URL]];

   // Spoof iOS Safari headers for sites that sniff the User Agent
   [req addValue:@"Mozilla/5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25" forHTTPHeaderField:@"User-Agent"];

   NSURLConnection *conn = [NSURLConnection connectionWithRequest:newRequest delegate:self];

   return YES;
} 
Run Code Online (Sandbox Code Playgroud)

我的NSURLConnection代表:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSString *mime = [response MIMEType];

    if ([mime isEqualToString:@"application/vnd.apple.pkpass"] && ![_data length]) {

        _data = nil; // clear any old data
        _data = [[NSMutableData alloc] init];

        [_webPanel stopLoading];
    }
}

-(void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    [_data appendData:data];
    NSLog(@"Size: %d", [_data length]);
}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{

    if ([_data length]) {

        PKAddPassesViewController  *pkvc = [PassKitAPI  presentPKPassFileFromData:_data];
        pkvc.delegate = self;
        [self presentViewController:pkvc
                           animated:YES
                         completion:nil];
    }
}
Run Code Online (Sandbox Code Playgroud)

NSURLConnection建立连接时直接调用的,没有代表做工精细UIWebView.但是,当我尝试NSURLConnectionUIWebView委托启动一个时,传递下载失败,因为只下载了80%左右的.pkpass(我在_data变量和Content-Length头中得到了一个随机的字节不匹配).

所以,我的问题:

  1. 是否有更简单的方法来MIME直接从UIWebViewDelegate方法获取类型?
  2. 如果没有,那么我是否以正确的方式打开并行NSURLConnection,或者有更好的方法吗?
  3. 如果NSURLConnection是要走的路,那么是什么导致它不能下载完整的文件呢?

Zee*_*han 0

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    NSURL *url = request.URL;
    NSURLRequest *req  = [NSURLRequest requestWithURL:url];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:req delegate:self];
    [conn start];
    return YES;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    NSString *mime = [response MIMEType];
    NSLog(@"%@",mime);

}
Run Code Online (Sandbox Code Playgroud)