2014-10-02 2 views
0

Я построил класс, который должен получить ibeacons. Насколько я знаю, я все делаю правильно. Но это не сработает. Мое приложение не запрашивает разрешения на размещение, и менеджер местоположений не начинает обновление. Я также установил атрибуты в plist.Swift - получить iBeacon - внешний класс

NSLocationWhenInUseUsageDescription

NSLocationAlwaysUsageDescription

Он работает только тогда, когда я инициализировать все правильно в AppDelegate. Как и в учебнике здесь.

http://ibeaconmodules.us/blogs/news/14702963-tutorial-swift-based-ibeacon-app-development-with-corelocation-on-apple-ios-7-8

Но я хочу, чтобы передать эту услугу к классу. Я не знаю, что я делаю неправильно. Я новичок в Swift, в Objective-C он всегда работал. Может ли кто-нибудь мне помочь?

Здесь код-

ViewController

импорт UIKit

класс ViewController: UIViewController, BeaconServiceProtocolDelegate {

override func viewDidLoad() { 
    super.viewDidLoad() 

    //Set BackgroundImage and hide Navigationbar 
    self.view.backgroundColor = UIColor(patternImage: UIImage(named:"bg")); 
    self.navigationController?.navigationBar.hidden = true 

    ////////////////////////create new Beacon Service which is looking for beacon which are given with the parameters 
    var beaconAdvertiseService = BeaconService(parauuidString: "F0018B9B-7509-4C31-A905-1A27D39C003C",parabeaconIdentifier:"iBeaconTalentTeamAudi"); 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 

} 

//Notification if our service found a beacon 
func sendLocalNotificationWithMessage(message: String!) { 
    let notification:UILocalNotification = UILocalNotification() 
    notification.alertBody = message 
    UIApplication.sharedApplication().scheduleLocalNotification(notification) 
} 

//Delegate from BeaconService 
func foundBeacon() { 
    println("Found Beacon") 
} 

}

и конечно класс - BeaconAdvertiseService

import Foundation 
import CoreBluetooth 
import CoreLocation 

//BeaconService Delegate 
protocol BeaconServiceProtocolDelegate 
{ 
    func foundBeacon() 
} 


import Foundation 
import CoreBluetooth 
import CoreLocation 

//BeaconService Delegate 
protocol BeaconServiceProtocolDelegate 
{ 
    func foundBeacon() 
} 

class BeaconService: NSObject, CLLocationManagerDelegate{ 

    let beaconServiceDelegate:BeaconServiceProtocolDelegate? 

    let uuidString:String//UUID Beacon as String 
    let beaconIdentifier:String//Identifier Beacon 
    let beaconUUID:NSUUID//UUID Beacon 
    let beaconRegion:CLBeaconRegion//Beacon Region 
    let locationManager:CLLocationManager ////location manager 

    ////////////////////////Init class (constructor) // Params UUID as String & and Identifier from beacon 
    init(parauuidString:String,parabeaconIdentifier:String) { 



     self.uuidString   = parauuidString 
     self.beaconIdentifier = parabeaconIdentifier 
     self.beaconUUID   = NSUUID(UUIDString: self.uuidString) 
     self.beaconRegion  = CLBeaconRegion(proximityUUID:self.beaconUUID,identifier: self.beaconIdentifier) 
     self.locationManager   = CLLocationManager(); 


     super.init() 
     self.initLocationMangager() 

    } 

    ////////////////////////Init location manager 
    private func initLocationMangager() 
    { 
     println(self.locationManager) 

     if(self.locationManager.respondsToSelector("requestAlwaysAuthorization")) { 
      locationManager.requestAlwaysAuthorization() 
     } 

     self.locationManager.delegate = self 
     self.locationManager.pausesLocationUpdatesAutomatically = false 

     self.locationManager.startMonitoringForRegion(beaconRegion) 
     self.locationManager.startRangingBeaconsInRegion(beaconRegion) 
     self.locationManager.startUpdatingLocation() 
    } 


    ////////////////////////////////////////////////////////// 
    ////////////////////////////////////////////////////////// 
    ////////////////////////LocationManager Delegates 
    ////////////////////////////////////////////////////////// 
    ////////////////////////////////////////////////////////// 

    ////////////////////////LocationManager didStartMonitoringForRegion 
    func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) { 
     manager.startRangingBeaconsInRegion(region as CLBeaconRegion) 
     println("Did Start") 
    } 

    ////////////////////////LocationManager didEnterRegion 
    func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) { 
     manager.startRangingBeaconsInRegion(region as CLBeaconRegion) 
    } 

    ////////////////////////LocationManager didRangeBeacons 
    func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) { 

      var message:String = "" 

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

       switch nearestBeacon.proximity { 
       case CLProximity.Far: 
        message = "Far" 
       case CLProximity.Near: 
        message = "Near" 
       case CLProximity.Immediate: 
        message = "Immediate" 
       case CLProximity.Unknown: 
        return 
       } 
      } else { 
       message = "No Beacons" 
      } 

      //Call BeaconServiceDelegate 
      beaconServiceDelegate?.foundBeacon() 
    } 

    ////////////////////////LocationManager monitoringDidFailForRegion 
    func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) { 
     println(error) 
    } 

    ////////////////////////LocationManager didExitRegion 
    func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) { 
     manager.stopRangingBeaconsInRegion(region as CLBeaconRegion) 

    } 

} 

ответ

0

Похоже, что вы назначаете ваш рекламировать услугу локальной переменной в конце вашего viewDidLoad. Этот экземпляр будет уничтожен в конце этого метода (одна строка позже;)

Обязательно присвойте рекламодателю переменную или свойство экземпляра и назначьте себя (своего диспетчера представлений) в качестве делегата для вашего рекламодателя.

Это должно сделать трюк.

0

Я вижу, по крайней мере, одна вещь очень просто. Похоже, метод initLocationMangager() так и не получил. Вероятно, вы должны добавить вызов этого метода из метода init(parauuidString:String,parabeaconIdentifier:String).

0

Извините, что забыл, что я вынул. Но это также не идет с вызывающим

self.initLocationMangager()