Reputation: 19
I have to call method that retrieve data from server every hour in background. For instance when click home button disappear app. Then run code every hour and send local notifications. My code is
@objc func getCustomerOrders() {
let headers = [
"accept": "application/json",
"Username": "[email protected]",
"Password": "1234"
]
Alamofire.request("https://leathermaster.bse.com.cy/api/getcompletedorders", method:.get, encoding: JSONEncoding.default, headers: headers) .responseJSON { response in
switch (response.result) {
case .success( _):
do {
self.orders = try JSONDecoder().decode([OrderComplete].self, from: response.data!)
if self.orders.count > 0 {
for i in 0...self.orders.count-1 {
if self.orders[i].PhoneNumber == self.preferences.string(forKey: "phone") {
print("TransactionStatus \(self.orders[i].TransactionStatus)")
let date = self.orders[i].TransactionDate.date.replacingOccurrences(of: ".000000", with: "")
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "\(self.preferences.string(forKey: "firstname")!) \(self.preferences.string(forKey: "surname")!) your order with \(self.orders[i].TransactionCode) transaction code is ready for pickup"
content.body = "\(self.orders[i].TransactionStatus) Date Time: \(date)"
content.sound = .default
content.userInfo = ["value": "Data with local notification"]
let fireDate = Calendar.current.dateComponents([.day, .month, .year, .hour, .minute, .second], from: Date().addingTimeInterval(20))
//let trigger = UNCalendarNotificationTrigger(dateMatching: fireDate, repeats: true)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3600, repeats: false)
let request = UNNotificationRequest(identifier: "reminder", content: content, trigger: trigger)
center.add(request) { (error) in
if error != nil {
print("Error = \(error?.localizedDescription ?? "error local notification")")
}
}
}
}
}
} catch let error as NSError {
print("Failed to load: \(error)")
}
case .failure(let error):
print("Request error: \(error.localizedDescription)")
}
}
}
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(getCustomerOrders), name: UIApplication.willResignActiveNotification, object: nil)
I try to run code when app is closed and send periodically local notifications in swift iOS. I hope to give me a solution an expertise programmer.
Upvotes: 0
Views: 99
Reputation: 438162
See Choosing Background Strategies for Your App. Or WWDC 2020 video Background execution demystified.
Bottom line, you can request background app refresh, but the OS will run this at a time of its own discretion (based upon wifi and power availability as well as historical app usage patterns). If you want to proactively notify your user if there is new content, you may have to use a push notification. See Pushing background updates to your App.
FWIW, you might want to also see Refreshing and Maintaining Your App Using Background Tasks sample.
Upvotes: 0