Swift3 : How to load html file to WKWebview from document directory - swift

Can anyone explain how to load local html file to WKWebView?
I tried with the below code works well in simulator but not on device
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath: String = path[0]
let fileManager = FileManager()
let destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath + "/" + "\(NameF.fileName)/\(NameF.Languages)/page_\(i + 1 ).html")
print("D2\(destinationURLForFile)")
let request = NSURLRequest(url: destinationURLForFile)
webView!.load(request as URLRequest)
Any suggestions would be helpful!

Thank you for your response guys and for who tried my question.Finally found the answer by opening the local file and read its content and then send that string into a WKWebview
And the piece of code is
do{
let fileName = try String(contentsOf: destinationURLForFile)
print("fileName is equal to\(fileName)")
webView.loadHTMLString(fileName, baseURL: destinationURLForFile)
}catch{
}

Related

Playing songs downloaded into the cache directory

Downloading an mp3 and saving it into the Library/caches folder works, But accessing it later doesn't.
Checking if the song really exists, i opened up Finder and went to the simulator folders. and my folder looks like this:
My song is located at: Library/Caches/Digger/Flower.mp3
Trying to access this using AVPlayer:
let folderName = "Digger"
let fileName = "Flower.mp3"
let url = FileManager.default
.urls(for: .cachesDirectory, in: .userDomainMask)[0]
.appendingPathComponent(folderName).appendingPathComponent(fileName)
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true) {
player.play()
}
But it doesn't work.
Simulator screenshot upon runtime:
Your URL handling is incorrect.
Replace these lines:
var urlString = url.absoluteString
print("MyPath: \(urlString)")
urlString.removeSubrange(urlString.range(of: "file://")!)
let player = AVPlayer(url: URL(string: urlString)!)
with:
let player = AVPlayer(url: url)
url already is the URL that you need. No need to try to convert it in any way.
For reference, use url.path to convert a file URL into a path string. And if you need to create a URL from a path string, use URL(fileURLWithPath:), not URL(string:). Only use URL(string:) with a string that has a URL scheme such as file://, https://, etc.

swift save file after download Alamofire

download and save file
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
// var fileURL = self.createFolder(folderName: downloadFolderName)
var fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = URL(string : currentFile.link )
fileURL = fileURL.appendingPathComponent((fileName?.lastPathComponent)!)
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}
Alamofire.download(currentDownloadedFile.link , to: destination).response(completionHandler: { (DefaultDownloadResponse) in
print("res ",DefaultDownloadResponse.destinationURL!);
completion(true)
})
but when i wont to check file in this dirrectory i get nil
let filemanager:FileManager = FileManager()
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let files = filemanager.enumerator(atPath: fileURL.absoluteString) // = nil
while let file = files?.nextObject() {
print(file)
}
if i save local path to file and after reload app wont to share it -> "share" app cant send file (mb cant found it)
can u pls help me. how it works ? why when i print all files he didnt find it? how to save file who after reboot app it will be saved in same link
You are using the wrong API
For file system URLs use always path, absoluteString returns the full string including the scheme (e. g. file:// or http://)
let files = filemanager.enumerator(atPath: fileURL.path)

How to read data from a file in the App's bundle I macOS?

I'm trying to read the data from a txt file on macOS. I use String(contentsOf:) and Bundle.main.path(forResource:) like I would on iOS. However, this doesn't work on macOS. I have tried several solutions from other posts but because of macOS they don't seem to work.
Thanks in advance.
Edit:
My code:
let path = Bundle.main.path(forResource: "file", ofType: "txt")! // no error
let url = URL(string: path)! // no error
let contents: String
do {
contents = try String(contentsOf: url)
} catch {
print(error) // Error Domain=NSCocoaErrorDomain Code=262 "The file couldn’t be opened because the specified URL type isn’t supported."
contents = "ERROR"
}
print(contents)
I can save the data to a folder on disk, but I want to ship this file with my app.
URL(string is the wrong API. It's only for URL strings starting with a scheme (http://, file://)
For file system paths you have to use URL(fileURLWithPath.
But in this situation there is a much better way
Replace
let path = Bundle.main.path(forResource: "file", ofType: "txt")!
let url = URL(string: path)! // no error
with
let url = Bundle.main.url(forResource: "file", withExtension: "txt")

How to get user home directory path (Users/"user name") without knowing the username in Swift3

I am making a func that edits a text file in the Users/johnDoe Dir.
let filename = "random.txt"
let filePath = "/Users/johnDoe"
let replacementText = "random bits of text"
do {
try replacementText.write(toFile: filePath, atomically: true, encoding: .utf8)
}catch let error as NSError {
print(error: + error.localizedDescription)
}
But I want to be able to have the path universal. Something like
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
but for the JohnDoe folder. I haven't been able to find any documentation on how to do this. The closest thing I could find mentioned using NSHomeDirectory(). And I am not sure how to use it in this context.
when I try adding it like...
let fileManager = FileManager.default
let downloadsURL = FileManager.default.urls(for: NSHomeDirectory, in: .userDomainMask).first! as NSURL
let downloadsPath = downloadsURL.path
I get an error:
"Cannot Convert value of type 'String' to expected argument type 'FileManager.SearchPathDirectory'"
I've tried it .NSHomeDirectory, .NSHomeDirectory(), NShomeDirectory, NShomeDirectory()
You can use FileManager property homeDirectoryForCurrentUser
let homeDirURL = FileManager.default.homeDirectoryForCurrentUser
If you need it to work with earlier OS versions than 10.12 you can use
let homeDirURL = URL(fileURLWithPath: NSHomeDirectory())
print(homeDirURL.path)
There should be an easier way but -- at worst -- this should work:
let filePath = NSString(string: "~").expandingTildeInPath
Swift 5 (and maybe lower)
let directoryString: String = NSHomeDirectory()
let directoryURL: URL = FileManager.default.homeDirectoryForCurrentUser
Maybe
FileManager.homeDirectoryForCurrentUser: URL
It's listed as "beta" for 10.12, though.

how to convert .pdf file to base64 string in swift 2.0?

I have to upload document in swift , I have to do this using the iCloud , so that I can upload file to my server using icloud
Swift 3.x
let filePath = ... //URL of the PDF
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
Drag the pdf file to the project or five the path before to hold
let url1 = Bundle.main.url(forResource: "pdffilename without extension", withExtension: "pdf")
let one1 = NSData(contentsOf: url1!)
let pdfstring:String = one1!.base64EncodedString(options: .endLineWithLineFeed)
print(pdfstring)
let filePath = "" // real path of the pdf file
let fileData = NSData(contentsOfFile: path)
let fileStream = data.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) // base64 string
Where would you pick the file, That file path has to be given:
First generate the base64 string you can use it
Then generate the bytes
Which one comfortable could use it.
do {
let fileData = try Data.init(contentsOf: filePath!)
let fileStream:String = fileData.base64EncodedString(options: NSData.Base64EncodingOptions.init(rawValue: 0))
let decodeData = Data(base64Encoded: fileStream, options: .ignoreUnknownCharacters)
body.append(decodeData!)
}
catch { }