Computer >> Máy Tính >  >> Lập trình >> IOS

Làm thế nào để kiểm tra xem một chương trình iOS đang ở chế độ nền hay nền?

Biết khi nào ứng dụng ở nền trước hay trong nền là điều quan trọng khi là nhà phát triển iOS, chúng ta cần xử lý nhiều sự kiện như tải xuống trong nền, sự kiện nếu ứng dụng xuất hiện ở nền trước.

Ở đây chúng ta sẽ xem cách kiểm tra xem ứng dụng đang ở chế độ nền hay nền trước.

Chúng tôi sẽ sử dụng Trung tâm thông báo cho việc đó,

Để đọc thêm về nó, bạn có thể tham khảo tài liệu apple.

https://developer.apple.com/documentation/foundation/notificationcenter

Một cơ chế gửi thông báo cho phép truyền phát thông tin cho các quan sát viên đã đăng ký. Chúng tôi sẽ thêm người quan sát vào cùng và sẽ nhận cuộc gọi.

Bước 1 - Mở Xcode → Dự án mới → Ứng dụng một lần xem → Đặt tên cho nó là “ForegroundBackground”

Bước 2 - Trong viewDidLoad, tạo một đối tượng của Trung tâm thông báo

let notificationCenter = NotificationCenter.default

Bước 3 - Thêm trình quan sát cho hậu cảnh và tiền cảnh

notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)

notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)

Bước 4 - Thực hiện các phương pháp bộ chọn

@objc func foregroundCall() {
   print("App moved to foreground")
}
@objc func backgroundCall() {
   print("App moved to background!")
}

Bước 5 - Đặt điểm ngắt và chạy ứng dụng.

Hoàn thành mã

import UIKit
class ViewController: UIViewController {
   override func viewDidLoad() {
      super.viewDidLoad()
      let notificationCenter = NotificationCenter.default
      notificationCenter.addObserver(self, selector: #selector(backgroundCall), name: UIApplication.willResignActiveNotification, object: nil)
      notificationCenter.addObserver(self, selector: #selector(foregroundCall), name: UIApplication.didBecomeActiveNotification, object: nil)
   }
   @objc func foregroundCall() {
      print("App moved to foreground")
   }
   @objc func backgroundCall() {
      print("App moved to background!")
   }
}