This question already has answers here:
Swift - encode URL
(19 answers)
How to use stringByAddingPercentEncodingWithAllowedCharacters() for a URL in Swift 2.0
(6 answers)
Closed 3 years ago.
Here i trying to open URL with .pdf extension in Safari Browser. But code is not working I'm getting nil in URL. But when i tried URL like "www.google.com" it's working fine
Code
let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"
guard let url = URL(string: cerificateURl) else {
return
}
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
Thanks in Advance
Try this one:
guard let url = URL(string: "your web pdf file link here or you can set from local directory path")
else { return }
UIApplication.shared.open(url)
Try This one.
let cerificateURl = "https://file-examples.com/wp-content/uploads/2017/10/file-sample_150kB.pdf"
if let myURL = URL(string: url) {
if let data = try? Data(contentsOf: myURL) {
webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: myURL
}
}
Related
This question already has answers here:
Swift - encode URL
(19 answers)
Closed 1 year ago.
I want to download image and when I run app my app crashed because the image string of json file is like this :
images/product/2021-05-02T09-47-17.699Z-download (2).jpg
there is a distance between download and (2) in my json file and its the problem that make an app crash , in browser its worked but in Xcode not , what's your idea to solve it?
and here is a part of my code when I want to download image :
let imageUrl = URL(string: "http://5.63.13.16:8080/\(item.image.first!)")!
if let data = try? Data(contentsOf: imageUrl) {
cellol.offerImageView.image = UIImage(data: data)
}
you can just use it
func stringCorrection( _ text:String) -> String{
return text.replacingOccurrences(of: " ", with: "", options: NSString.CompareOptions.literal, range: nil)
}
use: -
let imageUrl = URL(string: "http://5.63.13.16:8080/\(stringCorrection(item.image.first!))")!
if let data = try? Data(contentsOf: imageUrl) {
cellol.offerImageView.image = UIImage(data: data)
}
i have tried everything on internet to add a PDFViewer in my app. im working with ios 12. im asking you to help me understand what is the possible ways to add a pdf and a solution that can solve it in a easy way for my low experience with swift coding. thank you
We can use our native UIDocumentInteractionController for the same.
Follow below steps :
Step 1
var documentInteractionController = UIDocumentInteractionController()
Step 2
self.documentInteractionController.delegate = self
Step 3
func openDocument(atURL url: URL, screenTitle: String) {
self.documentInteractionController.url = url
self.documentInteractionController.name = screenTitle
self.documentInteractionController.delegate = self
self.documentInteractionController.presentPreview(animated: true)
}
Step 4 : Implement UIDocumentInteractionControllerDelegate
extension ViewController: UIDocumentInteractionControllerDelegate {
// when a document interaction controller needs a view controller for presenting a document preview.
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self.navigationController ?? UIViewController()
}
}
Some helper methods :
a) View Pdf
func viewPdf(urlPath: String, screenTitle: String) {
// open pdf for booking id
guard let url = urlPath.toUrl else {
print("Please pass valid url")
return
}
self.downloadPdf(fileURL: url, screenTitle: screenTitle) { localPdf in
if let url = localPdf {
DispatchQueue.main.sync {
self.openDocument(atURL: url, screenTitle: screenTitle)
}
}
}
}
b) function for download file
// method for download pdf file
func downloadPdf(fileURL: URL, screenTitle: String, complition: #escaping ((URL?) -> Void)) {
// Create destination URL
if let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
let destinationFileUrl = documentsUrl.appendingPathComponent("\(screenTitle).pdf")
if FileManager.default.fileExists(atPath: destinationFileUrl.path) {
try? FileManager.default.removeItem(at: destinationFileUrl)
}
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url: fileURL)
let task = session.downloadTask(with: request) { tempLocalUrl, response, error in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
complition(destinationFileUrl)
} catch let writeError {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "N/A")")
}
}
task.resume()
} else {
complition(nil)
}
}
here I am Downloading PDF and store on in File And Open That file in Quick Look
Here I am sharing screen
enter image description here
Reference link: https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller
If you just need to present the PDF, you could use a WebView from WebKit and pass the data using the mimetype application/pdf.
like this:
webView.load(data, mimeType: "application/pdf", characterEncodingName: "UTF-8", baseURL: baseURL)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have pdf url, I want to know the code how to store that pdf in my phone memory. I want to store that pdf and want to view that pdf from phone. I am using swift 4 and Xcode for coding
Swift 4
Call this function only pass url and after downloading it will be return file url........
func get_file(httpUrl:String)
{
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = URL(string: httpUrl)!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: url)
request.httpMethod = "GET"
let task = session.dataTask(with: request, completionHandler:
{
data, response, error in
if error == nil
{
if let response = response as? HTTPURLResponse
{
if response.statusCode == 200
{
if let data = data
{
if let _ = try? data.write(to: destinationUrl, options: Data.WritingOptions.atomic)
{
print(destinationUrl.absoluteString)
}
else
{
print(error!)
}
}
else
{
print(error!)
}
}
}
}
else
{
print(error!)
}
})
task.resume()
}
here you caught your file ..
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let url = URL(string: file_str)!
let destinationUrl = documentsUrl.appendingPathComponent(url.lastPathComponent)
I am converting base64 to pdf file in local.
func saveBase64StringToPDF(_ base64String: String)
{
guard
var documentsURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last,
let convertedData = Data(base64Encoded: base64String)
else {
//handle error when getting documents URL
return
}
documentsURL.appendPathComponent("yourFileName.pdf")
do {
try convertedData.write(to: documentsURL)
} catch {
//handle write error here
}
print(documentsURL)
}
From above method I am getting a path pdf file
file:///Users/captivatesoft/Library/Developer/CoreSimulator/Devices/63D1814B-1010-4694-883E-D2EE75C386DD/data/Containers/Data/Application/1F39B567-F470-4B7E-9A9C-4723ADFDC428/Documents/yourFileName.pdf
Is there any way to download this pdf file or to show pdf in safari?
var pdfURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
pdfURL = pdfURL.appendingPathComponent( "example.pdf") as URL
let data = try! Data(contentsOf: pdfURL)
let webView = WKWebView(frame: CGRect(x:20,y:20,width:view.frame.size.width-40, height:view.frame.size.height-40))
webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
view.addSubview(webView)
To open the PDF in Safari you could just do
UIApplication.shared.openURL(URL(string: <the link for the PDF>))
Now to download a PDF or anything from a URL, you could just do
let pdfData = try? Data(contentsOf: URL(string: <the link for the PDF>))
NOTE: try Data(contentsOf: url) will block the thread, so you might want to do it on a different thread like this :
DispatchQueue.global.async { [weak self] in
if let pdfData = try? Data(contentsOf: url) {
// Now you can do anything with the data
}
}
First, you can not download pdf file in iOS, it means you cannot save pdf file in iBook or Album.
You can fetch pdf file data from file URL then you can do follows:
Open in Safari browser from the app.
You can show pdf file in WKWebView within the app.
You can use "QuickLook" framework to show the pdf file.
Using WebView:
if let url = URL(string:string) {
webView.load(URLRequest(url: url))
}
I am trying to learn iOS following a course and they ask to do the following:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//var string1 = "http://www.google.com"
//var string1 = "https://www.weather-forecast.com/locations/San-Antonio/forecasts/latest"
//var url = NSURL(string: string1)
var url = NSURL(string: "https://google.com")
print(url)
if url != nil {
let task = NSURLSession.sharedSession().dataTaskWithURL(url!, completionHandler: { (data, response, error) -> Void in
var urlError = false
if error == nil {
var urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(urlContent)
} else {
urlError = true
}
if urlError == true {
self.showError()
}
})
task.resume()
} else {
showError()
}
}
the app doesn't show any web page content and when debugging I find that the object for the url says that it is "unable to read data"
I have tried with http and https. I have tried with different web sites.
I have tried the address in the safari of the simulator and it loads.
Can someone tell me why is this not working
Thanks in advance.
gariva
You're using wrong encoding. The webpage you're trying to fetch (http://www.google.com/) uses ISO-8859-1.
I was able to reproduce your issue. Fetch worked when I changed encoding. Try this:
var urlContent = NSString(data: data!, encoding: NSISOLatin1StringEncoding)
For display web page you should use UIWebView element. Something like this:
let url = NSURL(string: "https://google.com")
let webView = UIWebView(frame: self.view.frame)
self.view.addSubview(webView)
webView.loadRequest(NSURLRequest(URL: url!))