2015-07-21 108 views
0

我想捕獲從iOS中的WKWebView下載zip文件。登錄後,轉到link,請求歸檔並單擊下載按鈕,不下載zip文件。但是,WKWebView確實在Web瀏覽器中顯示該文件,或者似乎這樣做(請參閱下面的屏幕截圖)。當試圖從網絡視圖下載文件時,我只是拉一個HTML文件。WKWebView從間接鏈接下載zip文件

Download Button Shows Up Zip File displayed in WKWebView

有人可以在這裏提供一些方向,對於正確的方法來捕捉和下載的zip文件?注意,zip文件沒有直接鏈接。 WKWebView委託方法的代碼和下面的下載處理程序。

webView的didFinishNavigation

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { 
    NSURLComponents *comps = [[NSURLComponents alloc] initWithURL:webView.URL 

              resolvingAgainstBaseURL:NO]; 
    comps.query = nil; 

    NSLog(@"did finish nav URL: %@", webView.URL); 

    if ([webView.URL.absoluteString isEqualToString:LI_DOWNLOAD_URL]) { 

     dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1.0 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{ 
      [DownloadHandler downloadFileFromURL:webView.URL completion:^(NSString *filepath) { 
       NSLog(@"%@",filepath); 

      }]; 
     }); 
    } 
    else if ([comps.string isEqual: LI_REDIRECT_CATCH1] || 
     [comps.string isEqual: LI_REDIRECT_CATCH2] || 
     [comps.string isEqual: LI_REDIRECT_CATCH3]) { 

     self.statusText.text = @"Tap the \"Sign In\" button to log into LinkedIn"; 
    } 
    else if ([comps.string isEqual: LI_EXPORT_PAGE]) { 
     NSString *javascript = @"javascript:" \ 
           "var reqBtn = document.getElementById('request-button');" \ 
           "var pndBtn = document.getElementById('pending-button');" \ 
           "var dwnBtn = document.getElementById('download-button');" \ 
           "if (reqBtn) {" \ 
           " window.scrollTo(reqBtn.offsetLeft, 0);" \ 
           " window.webkit.messageHandlers.dataExport.postMessage('willRequestData');" \ 
           " reqBtn.addEventListener('click', function() {" \ 
           "  window.webkit.messageHandlers.dataExport.postMessage('didRequestData');" \ 
           " }, false);" \ 
           "} else if (pndBtn) {" \ 
           " window.scrollTo(pndBtn.offsetLeft, 0);" \ 
           " window.webkit.messageHandlers.dataExport.postMessage('isRequestPending');" \ 
           "} else if (dwnBtn) {" \ 
           " window.scrollTo(dwnBtn.offsetLeft, 0);" \ 
           " window.webkit.messageHandlers.dataExport.postMessage('willDownloadData');" \ 
           " dwnBtn.onclick = function() {" \ 
           "  window.webkit.messageHandlers.dataExport.postMessage('didDownloadData');" \ 
           " };" \ 
           "}"; 

     [self.webView evaluateJavaScript:javascript completionHandler:nil]; 
    } 
} 

下載處理器

+ (void)downloadFileFromURL:(NSURL *)url completion:(void (^)(NSString *filepath))completion { 

    NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration]; 

    NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration]; 

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    request.HTTPMethod = @"POST"; 

    NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request 
                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 

      if (!error) { 

       dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{ 

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
        NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"linkedin-file-export.zip"]; 

        [data writeToFile:dataPath atomically:YES]; 

        completion(dataPath); 
       }); 
      } 
      else { 
       NSLog(@"%@",error); 

       completion([NSString string]); 
      } 
    }]; 
    [postDataTask resume]; 
} 

我已經通過使用一個UIWebView以及想這一點,並且我得到了相同的結果。在Android中,這可以通過下載監聽器完成。如果可用,我會接受這樣的方法,但我不認爲它是在iOS中。

感謝您的任何幫助。

回答

1

您正試圖在webview完成加載zip文件url後下載zip ..我認爲這種方法應該是停止加載zip文件url的webview,並允許您的API將文件下載到所需的路徑..

像下面的東西。下面的代碼片段假定zip文件URL的擴展.zip

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { 

    NSURLRequest *request = navigationAction.request; 
    NSString *fileExtension = [[request URL]absoluteString].pathExtension; 
    if(fileExtension.length && [fileExtension caseInsensitiveCompare:@"zip"] == NSOrderedSame){ 
     //Do not load the zip url in the webview. 
     decisionHandler(WKNavigationActionPolicyCancel); 
     //Instead use the API to download the file 
     [DownloadHandler downloadFileFromURL:[request URL] completion:^(NSString *filepath) { 
      NSLog(@"%@",filepath); 

     }]; 
    } 

    //Allow all other request types to load in the webview 
    decisionHandler(WKNavigationActionPolicyAllow); 
} 

很想知道這是否爲你工作。

+0

感謝回覆@Subbu。但是,這不起作用,因爲鏈接沒有fileExtension。如果是這樣,我會變得更好。我認爲問題是WKWebView和NSURLConnection不共享cookie。它會出現我需要手動將它們轉移到NSURLConnection下載。 –

+0

哦,好吧; @NoahLabhart是WKWebView不使用像UIWebView那樣的NSHTTPCookieStorage ..你是否想嘗試在這個委託方法中將URL與你的'LI_DOWNLOAD_URL'進行比較? – Subbu

+0

我也是。同樣的事情,它會嘗試將URL路由回加入頁面。這對我說cookie沒有設置。這意味着認證不會在WKWebView和NSURLConnection之間共享。 –