Does try? Data(contentsOf: URL) use caching? - ios

I'm seeing an issue where I'm running the below multiple times with different URLs, and I'm getting the same data back 'sometimes' (it seems random). I'm wondering if iOS is caching some pages and giving me back the same data and not actually going to the URL.
Is there a cache? If so, is there a way to clear it before each call?
if let dataString = try? Data(contentsOf: url!) {
let pageContent = String(data: dataString, encoding: String.Encoding.utf8)
}

Take a look at init(contentsOf:options:) which provides an option called NSData.ReadingUncached. That's evidence that the simple form is cached and an answer to how you can control whether its cached.
A better approach with even more control is via URLSession

There are some cached files in the cache directory - print FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
After loading an image from a remote url, I added an extension .jpg to the cached file name. And I could see the image.

Related

Swift: write JSON and save to iPhone File locally

I am learning how to write JSON format data to an iPhone. So with one button clicked, I want to save those data to the iPhone. I looked a simple look on how to write some simple text and saved it to the iPhone file and it worked. However, I tried to apply the same idea to JSON data but still haven't figure out. I tried:
Rather than having contents equal to some written text, I tried to put it as my data (jsondata).
But it does not seem working with
try jsondata.write(to: fileURL, atomically: false, encoding: .utf8)
#IBAction func writeFiles(_ sender: Any) {
let file = "\(UUID().uuidString).txt"
let contents = "Testing"
let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = dir.appendingPathComponent(file)
do {
try contents.write(to: fileURL, atomically: false, encoding: .utf8)
}
catch {
print("Error: \(error)")
}
}
Sorry I am a bit new and learning Swift at the moment
Thanks!
Here is a simple project for you to clone or browse the source files
https://github.com/eSpecialized/WriteJsonToFiles
The View Controller contains the example;
https://github.com/eSpecialized/WriteJsonToFiles/blob/master/WriteToFiles/ViewController.swift
Basically you need to do a few steps for writing;
Assemble your objects (Strings etc).
Convert to JSONEncoded Data using the JSONEncoder.
The actual 'Data' Object can write it's binary content to storage.
To read the data;
You need a JSONDecoder.
You need the FileContents in memory using Data(contents:...)
Decode the in-memory data back into the object like it was stored.
A more complicated example of reading and writing JSON to a Web Service API is on Medium here > https://medium.com/better-programming/json-parsing-in-swift-2498099b78f
The concepts are the same, the destination changes from a file in the users document folder to a web service API. I feel that it is adequate to get you started with reading and writing JSON.
The Medium article goes a step further with introducing you to Data Models and reading and writing those Data Model Structs using the Codable protocol.
Enjoy! :)

How to display any extension file from server to your mobile in swift ios?

I am very new to this IOS swift programming. So need some suggestion and help. I am creating an app in which I have to show different file coming from the server. Below is the kind of link from which my file data is coming.
http://demo.xxxx.com/dctm-rest/repositories/iol_ref2/objects/0900a18480383d14/content-media?format=pdf&modifier=&page=0
This above link is for pdf or it can be of any type (txt, doc, img etc) so I have tried so many things but I was unable to get a result.
Solutions What I have tried:-
With basic auth, I am requesting URL and getting contents from the file, so I was getting data from server and printing on console but when I tried to copy that contents to one file it says unable to copy says no such file or folder exist but I have properly defined the path location. Below is my code link which I have asked earlier.
How to read data from file placed in server through url link in ios swift (4)?
Someone suggested using Alamofire lib that also I have used but no luck. Below is the code which I have referred.
Alamofire: finished with error - code: -1001
So let me know what I am doing is correct or not or is there any new method or way I can try. I have tried web view too. So please help me with this.
Thanks in advance
I use code like this to download a file and store it locally.
let destination: DownloadRequest.DownloadFileDestination = { _, _ in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent(documentFilename)
return (fileURL, [.removePreviousFile])
}
Alamofire.download(url, to: destination).response { [unowned self] response in
// check download and call completion handler
}
What code did you use to download the file?

WebView not showing my html file

I have a webView in my ViewController. I have created a BullsEye.html file in my project and I want to show that html file in my web view. Following is my code
if let url = Bundle.main.url(forResource: "BullsEye",
withExtension: "html") {
if let htmlData = try? Data(contentsOf: url) {
let baseURL = URL(fileURLWithPath: Bundle.main.bundlePath)
webView.load(htmlData, mimeType: "text/html",
textEncodingName: "UTF-8", baseURL: baseURL)
}
}
The above code is written in viewDidLoad. What am I missing?
I ran your code as is and was able to make things work as seen here after changing the webView loader code. This tells me you likely have a UIWebView lurking somewhere, likely your view in storyboard.
I would recommend you make sure that you are consistently using WKWebView throughout:
Import WebKit in your class file
Have a valid output link to it if you are using a storyboard
If using a storyboard, ensure that you are using WKWebView and not the deprecated UIWebView
There is no problem with your source code itself, I think.
But maybe does Bundle.main.url(forResource: "BullsEye", withExtension: "html") return nil?
If so, you should check for the two things below:
Whether the file to be read is included in Copy Bundle Resources
Files to be included in the project are registered in TARGETS> Build Phases> Copy Bundle Resources.
Whether the file to be read exists in the project directory
Open the project directory in the Finder and check if the file you are trying to load actually exists.
Hope this helps!
Below code will help you.
func loadHtmlFile() {
if let fileurl = Bundle.main.url(forResource: "BullsEye", withExtension: "html") {
let request = URLRequest(url: fileurl!)
webView.loadRequest(request)
}
}
See - swiftdeveloperblog
Also if the code don't seem to work for you, make sure to open html file in any browser and check if it's a valid html file.

Swift 3 - WKWebView Load Local HTML not loading resource files

I was download my website from online to store in xcode project with a sub-folder and want to run in WKWebView locally. I found the webview loaded webpage miss all CSS/JS/Images resources. I search around the internet and still not working. Is webpage inside relative url incorrect or my code to get the Main Bundle location problem? Anyone can help. Thanks.
Xcode Project Structure
HTML Page Contents Sample
I wrote this code to load WKWebView
let htmlFile = Bundle.main.path(forResource: "provisiontech", ofType: "htm")
let html = try? String(contentsOfFile: htmlFile!, encoding: String.Encoding.utf8)
let baseURL = Bundle.main.resourceURL!.appendingPathComponent("pvtc")
webView.loadHTMLString(html!, baseURL: baseURL)
The webview has no access to the resource folder. You should use loadFileURL(_:allowingReadAccessTo:) instead. Preloading the data is not neccessary, e.g.:
let url = Bundle.main.url(forResource: "provisiontech", ofType: "htm")
webView.loadFileURL(url, allowingReadAccessTo:
Bundle.main.resourceURL!.appendingPathComponent("pvtc"))
Edit: If the webview still cannot access the resources, you should consider whether putting the page and all resources into the same folder.

How to access a computer file on a phone

I am using
let data = try?
NSString(contentsOfFile: "/Users/BenA**** 1/Desktop/textFile.txt",
encoding: String.Encoding.utf8.rawValue)
to access a file on my computer. When I test put the app on my phone, it obviously didn't work because it didn't have access to the file. How could I put this file on my phone and be able to access it from there? Thanks.
Include your "textFile.txt" in main bundle by drag and drop file in to xcode project, then access it by
class testViewController: UIViewController{
var data:String = ""
override func viewDidLoad() {
super.viewDidLoad()
let path = NSBundle.mainBundle().pathForResource("textFile", ofType: "txt")
data = try? NSString(contentsOfFile: path!, encoding: ENCODING)
}}
Try this way to access 'data' in rest of code.
Hope this help.
To simulate the behavior of iOS enable the sandbox on macOS.
Now you can access files only in the container of the app.
Nevertheless the predefined folders like Documents, Library etc. still exist.
To have access to that directories there a method of NSFileManager. For example one of the most important directories in iOS is the Documents directory.
let documentsFolderURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomain: .UserDomainMask).first!
You have to use that method each time you need to get the URL of that particular directory because for security reasons the absolute path will change.

Resources