我有一个使用基本身份验证加载PDF的UIWebView
,如下所示
NSURL* url = [[NSURL alloc] initWithString:_urlString];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", usr, pwd];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]];
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[mutableRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
[_webView loadRequest:mutableRequest];
有没有办法让我轻松地将此PDF文件保存到磁盘上?我试过这个,但失败了:
NSData *fileData = [[NSData alloc] initWithContentsOfURL:_webView.request.URL];
我的网址如下所示:www.domain.com/files/foo.pdf
-initWithContentsOfURL:
NSData
方法执行简单的HTTP GET,但您需要设置一些授权参数,这就是它失败的原因。
为避免下载两次数据,您可以使用NSURLSession
下载、保存并使用UIWebView
-loadData:MIMEType:textEncodingName:baseURL:
加载它。
NSMutableURLRequest *mutableRequest = //Your Custom request with URL and Headers
[[[NSURLSession sharedSession] dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if (data)
{
//SaveDataIntoDisk
dispatch_async(dispatch_get_main_queue(), ^(){
[_webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil];
});
}
}] resume];
对于 Swift :
let webView = UIWebView()
let url = URL(string: "")!
let urlRequest : URLRequest = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: urlRequest , completionHandler: { (data, urlResponse, error) in
if (data != nil){
DispatchQueue.main.async {
webView.load(data!, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: url)
}
}
})
task.resume()
另一种方法:- 您可以下载PDF文件数据并将其保存在临时目录或首选目录中。 然后使用该保存的目录在 WebView 中打开该文件。
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data, error == nil else {
return
}
//MARK:- Now Saving the Document Data into Directory. I am using the temp directory you can change it to yours.
let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
self.tmpURL = tempDirectory.appendingPathComponent(response?.suggestedFilename ?? "fileName.png")
do {
try data.write(to: self.tmpURL! )
} catch {
print(error)
}
DispatchQueue.main.async {
//MARK:- Instead of using MIME type and NSData .now you can use the file directory to open the file in WEBView
self.webView.loadFileURL(self.tmpURL!, allowingReadAccessTo: self.tmpURL!)
}
}