Contact Us

Use the form on the right to contact us.

You can edit the text in this area, and change where the contact form on the right submits to, by entering edit mode using the modes on the bottom right. 


Oak Ridge, TN, 37830
United States

Swift-Snips

Sending data through Notifications : Swift 3

Wade Cantley

Here I am using the real-world example of sending data through a notification by sending beacon data to a listener every time the CoreLocation refreshes.  This is intended to demonstrate how the notification services can transmit data to a listener.

// /* 1 */ - In the AppDelegate I am sending a notification 
//every time CoreLocation hears a set of beacons.

// /* 2 */ - In another class, I am listing for the 
// Notice and pass along the data to a method.

// /* 3 */ - Do somethign with the data when the 
// method receives it.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// APPDELEGATE.SWIFT
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

// Later in code a delegate fires off with beacon data...
    
func beaconManager(manager: KTKBeaconManager, didRangeBeacons beacons: [CLBeacon], inRegion region: KTKBeaconRegion) {
    
    //Sends out a notification with a beacon array.
    /* 1 */ NSNotificationCenter.defaultCenter().postNotificationName("sendAllBeacons", object: beacons)
    
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
// LISTBEACONS2.SWIFT
class ListBeacons2: UITableViewController {

    // When the view loads, it starts listening for a notificaiton.
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Listen for a message containing an array of beacons
        /* 2 */ NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ListBeacons.getAllBeacons),  name: "sendAllBeacons", object: nil)
    }

    
    func getAllBeacons(notification: NSNotification){
        
        //Do something with the notification data which, in this example,
        // is cast into an array.
        /* 3 */ var beacons = Array(arrayLiteral: notification.object!)
        beacons = beacons[0] as! [CLBeacon]
    }
}