xcode从webview下载文件

时间:2016-04-12 09:04:28

标签: ios download uiwebview nsurl

我的问题是,如果我有uiwebview并且我想从用户点击下载链接时从任何网站下载文件我想获得此文件的扩展名(文件类型)而不加载网址时他点击它所以我可以向他显示警报视图,询问他是否要下载它。

例如,有这样的网址 https://www.download.com/file=knwhuchuen

此网址没有扩展名,但是当用户点击它时,它会向他显示mp4或mp3或zip文件?!

我使用此代码但它对我不起作用,有没有其他方法可以做到这一点

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

    if (navigationType == UIWebViewNavigationTypeLinkClicked || navigationType == UIWebViewNavigationTypeBackForward || navigationType == UIWebViewNavigationTypeFormSubmitted) {


        NSString *RequestURL     = [NSString stringWithFormat:@"%@",request.URL];

        NSURLSession *session    = [NSURLSession sharedSession];
        [[session dataTaskWithURL:[NSURL URLWithString:RequestURL]completionHandler:^(NSData *data,NSURLResponse *response,NSError *error)
          {
              dispatch_async(dispatch_get_main_queue(), ^{
                  if ([[NSThread currentThread] isMainThread])
                  {
                      if (!error)
                      {
                          NSString *mime = [response MIMEType];
                          CFStringRef mimeType  = (__bridge CFStringRef)mime;
                          CFStringRef uti       = UTTypeCreatePreferredIdentifierForTag(kUTTagClassMIMEType, mimeType, NULL);
                          CFStringRef extension = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassFilenameExtension);
                          NSString    *FileTybe = (__bridge NSString *)(extension);

                          NSLog(@"Type =  %@",FileTybe);
                      }else
                      {
                          UIAlertController* alert = [UIAlertController alertControllerWithTitle:nil
                                                                                         message:@"internt issu"
                                                                                  preferredStyle:UIAlertControllerStyleAlert];
                          UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"try again" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

                          }];
                          [alert addAction:defaultAction];
                          [self presentViewController:alert animated:YES completion:nil];
                      }
                  }
              });

          }]resume];
    }
    return YES;
}

0 个答案:

没有答案