Bagaimana cara membuat notifikasi lokal?


114

Bagaimana saya bisa mengatur pemberitahuan lokal sehingga pada saat saya mengatur, aplikasi saya menghasilkan pemberitahuan / peringatan dengan pesan yang disesuaikan?

Jawaban:


98

Berikut ini contoh kode untuk LocalNotification yang berfungsi untuk proyek saya.

Objective-C:

Blok kode ini dalam AppDelegatefile:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        // Override point for customization after application launch.
        return YES;
    }

    // This code block is invoked when application is in foreground (active-mode) 
 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification" 
        delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

        [notificationAlert show];
       // NSLog(@"didReceiveLocalNotification");
    }

Kode ini memblokir dalam file .m apa pun ViewController:

-(IBAction)startLocalNotification {  // Bind this method to UIButton action
    NSLog(@"startLocalNotification");

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
    notification.alertBody = @"This is local notification!";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber = 10;

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];    
}

Kode di atas menampilkan AlertView setelah interval waktu 7 detik ketika ditekan pada tombol yang mengikat startLocalNotificationJika aplikasi di latar belakang maka itu ditampilkan BadgeNumbersebagai 10 dan dengan suara notifikasi default.

Kode ini berfungsi dengan baik untuk iOS 7.x dan di bawahnya tetapi untuk iOS 8 akan meminta kesalahan berikut pada konsol:

Mencoba menjadwalkan pemberitahuan lokal dengan peringatan tetapi belum mendapat izin dari pengguna untuk menampilkan peringatan

Ini berarti Anda perlu mendaftar untuk pemberitahuan lokal. Ini dapat dicapai dengan menggunakan:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

Anda juga dapat merujuk blog untuk pemberitahuan lokal.

Cepat:

AppDelegate.swiftFile Anda akan terlihat seperti ini:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    
    // Override point for customization after application launch.
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))

    return true
}

File swift (katakanlah ViewController.swift) di mana Anda ingin membuat pemberitahuan lokal harus berisi kode di bawah ini:

//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
    println("buttonIsPressed function called \(UIButton.description())")

    var localNotification = UILocalNotification()
    localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
    localNotification.alertBody = "This is local notification from Swift 2.0"
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
    localNotification.userInfo = ["Important":"Data"];
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = 5
    localNotification.category = "Message"

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}


//MARK: - viewDidLoad

class ViewController: UIViewController {

    var objButton : UIButton!
    . . .

    override func viewDidLoad() {
        super.viewDidLoad()

        . . .

        objButton = UIButton.buttonWithType(.Custom) as? UIButton
        objButton.frame = CGRectMake(30, 100, 150, 40)
        objButton.setTitle("Click Me", forState: .Normal)
        objButton.setTitle("Button pressed", forState: .Highlighted)

        objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)

        . . .
    }

    . . .
}

Cara yang Anda gunakan untuk bekerja dengan Pemberitahuan Lokal di iOS 9 dan di bawahnya sama sekali berbeda di iOS 10.

Tangkapan layar di bawah dari catatan rilis Apple menggambarkan ini.

Screenshot

Anda dapat merujuk dokumen referensi apple untuk UserNotification.

Di bawah ini adalah kode untuk pemberitahuan lokal:

Objective-C:

  1. Sedang App-delegate.hdigunakan file@import UserNotifications;

  2. Delegasi aplikasi harus sesuai dengan UNUserNotificationCenterDelegateprotokol

  3. Dalam didFinishLaunchingOptionspenggunaan di bawah kode:

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
           completionHandler:^(BOOL granted, NSError * _Nullable error) {
                  if (!error) {
                      NSLog(@"request authorization succeeded!");
                      [self showAlert];
                  }
    }];
    
    -(void)showAlert {
        UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
          style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"Ok clicked!");
        }];
    
        [objAlertController addAction:cancelAction];
    
    
        [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{            
        }];
    
    }
  4. Sekarang buat tombol di pengontrol tampilan mana saja dan di IBAction gunakan kode di bawah ini:

    UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
    
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger =  [UNTimeIntervalNotificationTrigger                                             triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten                                                                            content:objNotificationContent trigger:trigger];
    
    // 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        } else {
            NSLog(@“Local Notification failed“);
        }
    }];

Cepat 3:

  1. Sedang AppDelegate.swiftdigunakan fileimport UserNotifications
  2. Appdelegate harus sesuai dengan UNUserNotificationCenterDelegateprotokol
  3. Dalam didFinishLaunchingWithOptionspenggunaan di bawah kode

    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
        if error != nil {
            print("Request authorization failed!")
        } else {
            print("Request authorization succeeded!")
            self.showAlert()
        }
    }
    
    
    func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
    
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
    
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }
  4. Sekarang buat tombol di pengontrol tampilan mana saja dan di IBAction gunakan kode di bawah ini:

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notify-test"
    
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
    
    let center = UNUserNotificationCenter.current()
    center.add(request)

1
Apakah saya perlu menjalankan funcButtonIsPressed setelah menekan tombol? Bagaimana jika saya ingin aplikasi, secara default, memberikan pemberitahuan itu setiap minggu, haruskah saya menambahkannya ke viewDidLoad VC awal?
Dave G

1
Selain itu, mengapa file AppDelegate.swift Anda memiliki didFinishLaunchingWithOptions dua kali?
Dave G

"import UserNotifications" impor ini di ViewController Anda
iOS

52

Di file appdelegate.m tulis kode berikut di applicationDidEnterBackground untuk mendapatkan notifikasi lokal

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

11
Saat Anda menjadwalkan hanya SATU notifikasi menggunakan setScheduledLocalNotifications: tidak diperlukan. Ada metode scheduleLocalNotification yang membutuhkan satu argumen - pemberitahuan akan dijadwalkan. developer.apple.com/library/ios/DOCUMENTATION/UIKit/Reference/… :
Paul Brewczynski

16

Membuat notifikasi lokal cukup mudah. Ikuti saja langkah-langkah ini.

  1. Pada fungsi viewDidLoad () meminta izin pengguna bahwa aplikasi Anda ingin menampilkan pemberitahuan. Untuk ini kita bisa menggunakan kode berikut.

    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
    })
  2. Kemudian Anda dapat membuat tombol, lalu di fungsi tindakan Anda dapat menulis kode berikut untuk menampilkan notifikasi.

    //creating the notification content
    let content = UNMutableNotificationContent()
    
    //adding title, subtitle, body and badge
    content.title = "Hey this is Simplified iOS"
    content.subtitle = "iOS Development is fun"
    content.body = "We are learning about iOS Local Notification"
    content.badge = 1
    
    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    
    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)
    
    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
  3. Notifikasi akan ditampilkan, cukup klik tombol home setelah menekan tombol notifikasi. Seperti saat aplikasi berada di latar depan, notifikasi tidak ditampilkan. Namun jika Anda menggunakan iPhone X. Anda dapat menampilkan pemberitahuan bahkan saat aplikasi berada di latar depan. Untuk ini, Anda hanya perlu menambahkan delegasi yang disebut UNUserNotificationCenterDelegate

Untuk detail selengkapnya, kunjungi entri blog ini: Tutorial Pemberitahuan Lokal iOS


Apakah mungkin untuk mengulang notifikasi setiap hari dengan waktu pasif dan mengulang sampai aplikasi terbuka?
Mitul Marsoniya

@KashfaKhan dapatkah Anda memberi tahu saya, metode mana yang dijalankan saat aplikasi berada di latar belakang dan aplikasi tersebut menerima pemberitahuan?
ArgaPK

10

Diperbarui dengan Swift 5 Umumnya kami menggunakan tiga jenis Pemberitahuan Lokal

  1. Pemberitahuan Lokal Sederhana
  2. Pemberitahuan Lokal dengan Tindakan
  3. Pemberitahuan Lokal dengan Konten

Di mana Anda dapat mengirim pemberitahuan teks sederhana atau dengan tombol tindakan dan lampiran.

Menggunakan paket UserNotifications di aplikasi Anda, contoh berikut Minta izin notifikasi, siapkan dan kirim notifikasi sesuai dengan tindakan pengguna AppDelegate itu sendiri, dan gunakan pengontrol tampilan yang mencantumkan berbagai jenis pengujian notifikasi lokal.

AppDelegate

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

    let notificationCenter = UNUserNotificationCenter.current()
    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        //Confirm Delegete and request for permission
        notificationCenter.delegate = self
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        notificationCenter.requestAuthorization(options: options) {
            (didAllow, error) in
            if !didAllow {
                print("User has declined notifications")
            }
        }

        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
    }
    func applicationDidEnterBackground(_ application: UIApplication) {
    }
    func applicationWillEnterForeground(_ application: UIApplication) {
    }
    func applicationWillTerminate(_ application: UIApplication) {
    }
    func applicationDidBecomeActive(_ application: UIApplication) {
        UIApplication.shared.applicationIconBadgeNumber = 0
    }


    //MARK: Local Notification Methods Starts here

    //Prepare New Notificaion with deatils and trigger
    func scheduleNotification(notificationType: String) {

        //Compose New Notificaion
        let content = UNMutableNotificationContent()
        let categoryIdentifire = "Delete Notification Type"
        content.sound = UNNotificationSound.default
        content.body = "This is example how to send " + notificationType
        content.badge = 1
        content.categoryIdentifier = categoryIdentifire

        //Add attachment for Notification with more content
        if (notificationType == "Local Notification with Content")
        {
            let imageName = "Apple"
            guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
            let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
            content.attachments = [attachment]
        }

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let identifier = "Local Notification"
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        notificationCenter.add(request) { (error) in
            if let error = error {
                print("Error \(error.localizedDescription)")
            }
        }

        //Add Action button the Notification
        if (notificationType == "Local Notification with Action")
        {
            let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
            let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
            let category = UNNotificationCategory(identifier: categoryIdentifire,
                                                  actions: [snoozeAction, deleteAction],
                                                  intentIdentifiers: [],
                                                  options: [])
            notificationCenter.setNotificationCategories([category])
        }
    }

    //Handle Notification Center Delegate methods
    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.notification.request.identifier == "Local Notification" {
            print("Handling notifications with the Local Notification Identifier")
        }
        completionHandler()
    }
}

dan ViewController

import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var appDelegate = UIApplication.shared.delegate as? AppDelegate
    let notifications = ["Simple Local Notification",
                         "Local Notification with Action",
                         "Local Notification with Content",]

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    // MARK: - Table view data source

     func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return notifications.count
    }

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = notifications[indexPath.row]
        return cell
    }

     func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let notificationType = notifications[indexPath.row]
        let alert = UIAlertController(title: "",
                                      message: "After 5 seconds " + notificationType + " will appear",
                                      preferredStyle: .alert)
        let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
            self.appDelegate?.scheduleNotification(notificationType: notificationType)
        }
        alert.addAction(okAction)
        present(alert, animated: true, completion: nil)
    }
}

1
- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

Ini berfungsi, tetapi di iOS 8.0 dan yang lebih baru , aplikasi Anda harus mendaftar untuk pemberitahuan pengguna menggunakan -[UIApplication registerUserNotificationSettings:]sebelum dapat menjadwalkan dan menyajikan UILocalNotifications, jangan lupakan ini.


- [UIApplication registerUserNotificationSettings:] akan mengesampingkan pengaturan notifikasi push. jadi Berhati-hatilah jika menggunakan notifikasi push yang dapat ditindaklanjuti.
Avijit Nagare

0

Pengguna iOS 8 ke atas, harap sertakan ini di Delegasi aplikasi untuk membuatnya berfungsi.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)])
    {
        [application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
    }

    return YES;
}

Dan kemudian menambahkan baris kode ini akan membantu,

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *notification = [[UILocalNotification alloc]init];
    notification.repeatInterval = NSDayCalendarUnit;
    [notification setAlertBody:@"Hello world"];
    [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
    [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
    [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];

}

0
-(void)kundanselect
{
    NSMutableArray *allControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
    NSArray *allControllersCopy = [allControllers copy];
    if ([[allControllersCopy lastObject] isKindOfClass: [kundanViewController class]]) 
    {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"kundanViewControllerHide"object:nil userInfo:nil];
    }
    else
    {
        [[NSUserDefaults standardUserDefaults] setInteger:4 forKey:@"selected"];
        [self performSegueWithIdentifier:@"kundansegue" sender:self];
    }
}

[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ApparelsViewControllerHide) name:@"ApparelsViewControllerHide" object:nil];


0

Saya berasumsi bahwa Anda telah meminta otorisasi dan mendaftarkan aplikasi Anda untuk pemberitahuan.

Berikut adalah kode untuk membuat notifikasi lokal

@available(iOS 10.0, *)
    func send_Noti()
    {
        //Create content for your notification 
        let content = UNMutableNotificationContent()
        content.title = "Test"
        content.body = "This is to test triggering of notification"

        //Use it to define trigger condition
        var date = DateComponents()
        date.calendar = Calendar.current
        date.weekday = 5 //5 means Friday
        date.hour = 14 //Hour of the day
        date.minute = 10 //Minute at which it should be sent


        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
        let uuid = UUID().uuidString
        let req = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)

        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.add(req) { (error) in
            print(error)
        }
    }
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.