I have the following piece of code I want to execute at app startup:
let database = "https://example.com" // A website.
let databaseURL = URL(string: "\(database)")!
var databaseRequest = URLRequest(url: databaseURL)
databaseRequest.httpMethod = "GET"
NSURLConnection.sendAsynchronousRequest(databaseRequest, queue: OperationQueue.main) {(response, data, error) in
guard let data = data else { return }
let databaseContents = data
let databaseFile = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("local.txt")
do {
try databaseContents.write(to: databaseFile)
} catch {
print(error.localizedDescription)
}
}
I want to give this code 10 seconds to run. If it takes longer than 10 seconds, abort it and do something else, like this:
print("ERROR: Could not retrieve list.")
let warningToUser = UIAlertController(title: "Error", message: "We couldn't retrieve your preferences, so they have been reset to default values. We will try again next tine you launch this app.", preferredStyle: .alert)
warningToUser.addAction(UIAlertAction(title: "OK", style: .default))
self.present(warningToUser, animated: true)
I don't even what to try. Any help is highly appreciated! Thank you!
CodePudding user response:
you need to specify the time interval of the URLrequest.
Just put this line in your code databaseRequest.timeoutInterval = 10
CodePudding user response:
You can set timeoutInterval and check the error after timeoutInterval.
let database = "https://example.com" // A website.
let databaseURL = URL(string: "\(database)")!
var databaseRequest = URLRequest(url: databaseURL, timeoutInterval: 10.0)
databaseRequest.httpMethod = "GET"
NSURLConnection.sendAsynchronousRequest(databaseRequest, queue: OperationQueue.main) {(response, data, error) in
if error != nil {
print("ERROR: Could not retrieve list.")
let warningToUser = UIAlertController(title: "Error", message: "We couldn't retrieve your preferences, so they have been reset to default values. We will try again next tine you launch this app.", preferredStyle: .alert)
warningToUser.addAction(UIAlertAction(title: "OK", style: .default))
self.present(warningToUser, animated: true)
}else {
guard let data = data else { return }
let databaseContents = data
let databaseFile = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("local.txt")
do {
try databaseContents.write(to: databaseFile)
} catch {
print(error.localizedDescription)
}
}
}