后台服务Alamofire Swift iOS

mwngjboj  于 2023-05-21  发布在  Swift
关注(0)|答案(1)|浏览(160)

我不得不在后台每小时调用一次从服务器中检索数据的方法。例如,当点击主页按钮消失的应用程序。然后每小时运行代码并发送本地通知。我的准则是

@objc func getCustomerOrders() {
        let headers = [
            "accept": "application/json",
            "Username": "info@bse.com.cy",
            "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)

我尝试在应用程序关闭时运行代码,并在Swift iOS中定期发送本地通知。我希望能给予我一个解决方案的Maven程序员.

3qpi33ja

3qpi33ja1#

参见Choosing Background Strategies for Your App。WWDC 2020视频Background execution demystified
底线是,您可以请求后台应用程序刷新,但操作系统将在自己的判断时间(基于WiFi和电源可用性以及历史应用程序使用模式)运行此操作。如果您希望在有新内容时主动通知用户,则可能必须使用推送通知。参见Pushing background updates to your App
FWIW,你可能还想看看Refreshing and Maintaining Your App Using Background Tasks示例。

相关问题