I have an Xcode app where currently txt files in the project display text data as a list. I can search through the lists and have buttons that will swap between different lists of information that you can look through.
The next task is I have URL connections to docx files on a SharePoint site. I am trying to use an URLsession function to connect to the URL links to download the documents to the document directory then have the application read the doc information to then be displayed as the txt info would.
The idea is that the docx files are a type of online update version of the data. So when the app is used and on wifi, the app can update the list data with the docx files.
I have code set up that should access the URL files but I am struggling to figure out how to read the data and access from this Documents directory. I have been looking online and so far I am at a loss on where to go here.
If anyone can help or provide some insight I would greatly appreciate it.
I can try and provide code samples to help explain things if that is needed.
I do use URLsession.
OK. Then let’s use this thread to focus on the networking side of things. Once you’ve got that working, you can start a new thread with an appropriate subtopic and tags for your next step.
URLSession is a very flexible API, so there are numerous ways you might use it to download a file. However, let’s explore a simple form. Imagine you have a button like this:
Button("Download") {
Task {
await runDownload()
}
}
That calls the runDownload() function, which looks like this:
func runDownload() async {
do {
print("will run download")
let url = URL(string: "https://example.com")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 60.0)
let (downloadURL, response) = try await URLSession.shared.download(for: request)
let httpResponse = response as! HTTPURLResponse
print("did run download, status: \(httpResponse.statusCode), downloadURL: \(downloadURL)")
} catch let error as NSError {
print("did not run download, error: \(error.domain) / \(error.code)")
}
}
That calls the download(for:delegate:) method, which downloads the file to a temporary location and returns you the HTTP response (response) and the file URL (downloadURL). You would normally look at the response to make sure it’s OK — for example, check that the statusCode is 200 — and, if so, move the file from its temporary location to wherever you want to store it in the long term.
Please try that and let me know how you get along.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"