Skip to content

Instantly share code, notes, and snippets.

@stephenlb stephenlb/1.swift

forked from ptrhub901/1.swift
Created Nov 15, 2017
Embed
What would you like to do?
Smart iBeacons in the Swift Programming Language
class Brain: NSObject, PNDelegate {
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
var channel = PNChannel()
var serverStatus = UILabel()
init() {
super.init()
}
}
func updateInterface(){
self.uuid.text = self.region.proximityUUID.UUIDString
self.major.text = "\(self.region.major)"
self.minor.text = "\(self.region.minor)"
self.identity.text = self.region.identifier
}
@IBAction func transmitBeacon(sender : UIButton) {
self.data = self.region.peripheralDataWithMeasuredPower(nil)
self.manager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
}
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {
if(peripheral.state == CBPeripheralManagerState.PoweredOn) {
println("powered on")
self.manager.startAdvertising(data)
self.beaconStatus.text = "Transmitting!"
} else if(peripheral.state == CBPeripheralManagerState.PoweredOff) {
println("powered off")
self.manager.stopAdvertising()
self.beaconStatus.text = "Power Off"
}
}
class ViewController: UIViewController, CLLocationManagerDelegate {
//our status label's referencing outlets
@IBOutlet var found : UILabel
@IBOutlet var uuid : UILabel
@IBOutlet var major : UILabel
@IBOutlet var minor : UILabel
@IBOutlet var accuracy : UILabel
@IBOutlet var distance : UILabel
@IBOutlet var rssi : UILabel
@IBOutlet var deal : UILabel
@IBOutlet var pubStatus : UILabel
//our UUID, make sure it's the same as the one you used for the emitter above
let uuidObj = NSUUID(UUIDString: "0CF052C2-97CA-407C-84F8-B62AAC4E9020")
//the core library objects used to detect iBeacons
var region = CLBeaconRegion()
var manager = CLLocationManager()
//our customer object
var cstmr = Customer()
}
override func viewDidLoad() {
super.viewDidLoad()
manager.delegate = self
region = CLBeaconRegion(proximityUUID: uuidObj, identifier: "com.pubnub.test")
cstmr.setup(deal, pubStatus: pubStatus)
}
@IBAction func startDetection(sender : UIButton) {
if(UIDevice.currentDevice().systemVersion.substringToIndex(1).toInt() >= 8){
self.manager.requestAlwaysAuthorization()
}
self.manager.startMonitoringForRegion(self.region)
self.found.text = "Starting Monitor"
}
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
self.found.text = "Scanning..."
manager.startRangingBeaconsInRegion(region as CLBeaconRegion) //testing line
}
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
manager.startRangingBeaconsInRegion(region as CLBeaconRegion)
self.found.text = "Possible Match"
}
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
self.found.text = "Error :("
println(error)
}
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
manager.stopRangingBeaconsInRegion(region as CLBeaconRegion)
reset()
}
func reset(){
self.found.text = "No"
self.uuid.text = "N/A"
self.major.text = "N/A"
self.minor.text = "N/A"
self.accuracy.text = "N/A"
self.rssi.text = "N/A"
cstmr.needDeal = true
cstmr.subscribeAttempt = true
self.deal.text = "Come on down to PubNub Cafe for a hot deal!"
}
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: NSArray!, inRegion region: CLBeaconRegion!) {
if(beacons.count == 0) { return }
var beacon = beacons.lastObject as CLBeacon
if (beacon.proximity == CLProximity.Unknown) {
self.distance.text = "Unknown Proximity"
reset()
return
} else if (beacon.proximity == CLProximity.Immediate) {
self.distance.text = "Immediate"
cstmr.getAdOfTheDay(beacon.major, minor: beacon.minor)
} else if (beacon.proximity == CLProximity.Near) {
self.distance.text = "Near"
//reset()
} else if (beacon.proximity == CLProximity.Far) {
self.distance.text = "Far"
}
self.found.text = "Yes!"
self.uuid.text = beacon.proximityUUID.UUIDString
self.major.text = "\(beacon.major)"
self.minor.text = "\(beacon.minor)"
self.accuracy.text = "\(beacon.accuracy)"
self.rssi.text = "\(beacon.rssi)"
}
class Customer: NSObject, PNDelegate {
let config = PNConfiguration(forOrigin: "pubsub.pubnub.com", publishKey: "demo", subscribeKey: "demo", secretKey: nil)
var connected = false
var deal = UILabel()
var pubStatus = UILabel()
var needDeal = true
var subscribeAttempt = true
init(){
super.init()
}
}
func setup(serverLabel: UILabel, minor: NSNumber, major: NSNumber) {
self.serverStatus = serverLabel
self.client = PubNub.clientWithConfiguration(configuration)
self.client.addListener(self)
self.client.subscribeToChannels(["my_channel"], withPresence: true)
}
func setup(deal: UILabel, pubStatus: UILabel) {
self.deal = deal
self.pubStatus = pubStatus
PubNub.setDelegate(self)
PubNub.setConfiguration(self.config)
PubNub.connect()
}
func getAdOfTheDay(major: NSNumber, minor: NSNumber) {
if(connected && subscribeAttempt) {
subscribeAttempt = false
var channel: PNChannel = PNChannel.channelWithName("minor:\(minor)major:\(major)CompanyName", shouldObservePresence: true) as PNChannel
PubNub.subscribeOnChannel(channel)
} else if (subscribeAttempt) {
deal.text = "connection error :("
}
}
func pubnubClient(client: PubNub!, didReceiveMessage message: PNMessage!){
println("message received!")
self.pubStatus.text = "Deal Received"
if(needDeal) {
self.needDeal = false
self.deal.text = "\(message.message)"
}
PubNub.unsubscribeFromChannel(message.channel)
}
func pubnubClient(client: PubNub!, didConnectToOrigin origin: String!) {
println("connected to origin \(origin)")
connected = true
self.pubStatus.text = "connected"
}
func pubnubClient(client: PubNub!, didSubscribeOnChannels channels: NSArray!) {
println("Subscribed to channel(s): \(channels)")
self.pubStatus.text = "Subscribed"
}
func pubnubClient(client: PubNub!, didUnsubscribeOnChannels channels: NSArray!) {
println("Unsubscribed from channel(s): \(channels)")
self.pubStatus.text = "Unsubscribed"
}
func pubnubClient(client: PubNub!, subscriptionDidFailWithError error: PNError!){
println("Subscribe Error: \(error)")
self.pubStatus.text = "Subscription Error"
}
func pubnubClient(client: PubNub!, didConnectToOrigin origin: String!) {
self.serverStatus.text = "Connected to PubNub"
}
func pubnubClient(client: PubNub!, didSubscribeOnChannels channels: NSArray!) {
self.serverStatus.text = "Ready to transmit"
}
func pubnubClient(client: PubNub!, subscriptionDidFailWithError error: PNError!){
println("Subscribe Error: \(error)")
self.pubStatus.text = "Subscription Error"
}
func pubnubClient(client: PubNub!, didUnsubscribeOnChannels channels: NSArray!) {
self.serverStatus.text = "Unsubscribed"
}
func pubnubClient(client: PubNub!, didDisconnectFromOrigin origin: String!) {
self.serverStatus.text = "Disconnected"
}3
func pubnubClient(client: PubNub!, didReceivePresenceEvent event: PNPresenceEvent!) {
if(event.type.value == PNPresenceEventType.Join.value) {
PubNub.sendMessage("Free Latte!", toChannel: event.channel)
}
}
func pubnubClient(client: PubNub!, didSendMessage message: PNMessage!) {
println("sent message on channel: \(channel.description)")
}
func pubnubClient(client: PubNub!, didFailMessageSend message: PNMessage!, withError error: PNError!) {
println(error.description)
}
class Server: NSObject, PNDelegate {
let configuration = PNConfiguration(publishKey: "demo", subscribeKey: "demo")
self.client = PubNub.clientWithConfiguration(configuration)
let channel = PNChannel.channelWithName("minor:6major:9CompanyName", shouldObservePresence: true) as PNChannel
//because you decide on major/minor numbers anyway, you can hardcode them into the channel string.
var serverStatus = UILabel()
init() {
super.init()
self.serverStatus = serverLabel
PubNub.setDelegate(self)
PubNub.setConfiguration(self.config)
PubNub.connect()
PubNub.subscribeOnChannel(self.channel)
}
func pubnubClient(client: PubNub!, didReceivePresenceEvent event: PNPresenceEvent!) {
if(event.type.value == PNPresenceEventType.Join.value) {
//you can modify the following line to send whatever information you want to the observer.
//you could also initiate an action such as a push notification.
PubNub.sendMessage("Free Latte!", toChannel: event.channel)
}
}
}
class ViewController: UIViewController, CBPeripheralManagerDelegate {
// our UIView's label referencing outlets
@IBOutlet var uuid : UILabel
@IBOutlet var major : UILabel
@IBOutlet var minor : UILabel
@IBOutlet var identity : UILabel
@IBOutlet var beaconStatus : UILabel
@IBOutlet var pubStatus : UILabel
// the UUID our iBeacons will use
let uuidObj = NSUUID(UUIDString: "0CF052C2-97CA-407C-84F8-B62AAC4E9020")
// Objects used in the creation of iBeacons
var region = CLBeaconRegion()
var data = NSDictionary()
var manager = CBPeripheralManager()
// An instance of our server class
var srvr = Server()
}
override func viewDidLoad() {
super.viewDidLoad()
self.region = CLBeaconRegion(proximityUUID: uuidObj, major: 9, minor: 6, identifier: "com.pubnub.test")
updateInterface()
brain.setup(self.serverStatus, minor: self.region.minor, major: self.region.major)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.