2015-11-29 36 views
1

下面的代碼對通知正常工作。但是,當我嘗試應用程序時,在近端和遠端之間通知太多。swift和iBeacon在locationManager中發起通知

extension AppDelegate: CLLocationManagerDelegate { 
func sendLocalNotificationWithMessage(message: String!) { 
    let notification:UILocalNotification = UILocalNotification() 
    notification.alertBody = message 
    UIApplication.sharedApplication().scheduleLocalNotification(notification) 
} 

func locationManager(manager: CLLocationManager!, 
    didRangeBeacons beacons: AnyObject[]!, 
    inRegion region: CLBeaconRegion!) { 
     NSLog("didRangeBeacons"); 
     var message:String = "" 

     if(beacons.count > 0) { 
      let nearestBeacon:CLBeacon = beacons[0] as CLBeacon 

      switch nearestBeacon.proximity { 
      case CLProximity.Far: 
       message = "You are far away from the beacon" 
      case CLProximity.Near: 
       message = "You are near the beacon" 
      case CLProximity.Immediate: 
       message = "You are in the immediate proximity of the beacon" 
      case CLProximity.Unknown: 
       return 
      } 
     } else { 
      message = "No beacons are nearby" 
     } 

     NSLog("%@", message) 
     sendLocalNotificationWithMessage(message) 
} 

}

它是用一種firedate聲明的方式嗎?喜歡的東西:

localNotification.fireDate = NSDate(timeIntervalSinceNow: 900) 

如果我把在 「FUNC sendLocalNotificationWithMessage」,它會firedate所有通知。我不得不以某種方式找到切換之後的一種方式?

或者可能是通知計數器?

回答

0

這聽起來像你想要做的是延遲一個新的通知顯示,如果你在過去的900秒內發送了另一個通知。如果這是目標,你可以這樣做:

var lastNotificationTime = 0.0 

func locationManager(manager: CLLocationManager!, 
    didRangeBeacons beacons: AnyObject[]!, 
    inRegion region: CLBeaconRegion!) { 
    NSLog("didRangeBeacons"); 
    var beaconVisible = false 
    var proximity = CLProximity.Unknown 
    if(beacons.count > 0) { 
     beaconVisible = true 
     let nearestBeacon:CLBeacon = beacons[0] as CLBeacon 
     proximity = nearestBeacon.proximity 
    } 
    else { 
     beaconVisible = false 
    } 

    if (NSDate.timeIntervalSinceReferenceDate() - lastNotificationTime > 900) { 
     lastNotificationTime = NSDate.timeIntervalSinceReferenceDate() 
     var message:String = "" 
     if beaconVisible { 
     switch proximity { 
     case CLProximity.Far: 
      message = "You are far away from the beacon" 
     case CLProximity.Near: 
      message = "You are near the beacon" 
     case CLProximity.Immediate: 
      message = "You are in the immediate proximity of the beacon" 
     case CLProximity.Unknown: 
      return 
     } 
     } 
     else { 
     message = "No beacons are nearby"; 
     } 
     NSLog("%@", message) 
     sendLocalNotificationWithMessage(message) 
    } 
    } 
+0

謝謝大衛。它運作良好! – Kibo