如何在xcode(swift)和phonegap中在后台将iPhone作为信标运行 [英] How to run iPhone as a beacon in background in both xcode(swift) and phonegap

查看:79
本文介绍了如何在xcode(swift)和phonegap中在后台将iPhone作为信标运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我设法创建了一个将手机转变为信标发射器的应用程序.

I managed to create an app which turns the phone into a beacon emitter.

它在xcode(Swift)和phonegap上正常工作.

It works fine on xcode (Swift) and phonegap .

对我来说,下一步是使其在后台作为信标工作(我正在为iOS 10开发).

The next step for me is making it work in the background as a beacon (I'm developing for iOS 10).

我在网上发现了与此类似的问题,但它们都已过时,即旧的ios,Objective-C和过时的插件

I found similar questions to this online but all of them were out of date ie old ios , objective-C and outdate plug-ins

如果有人可以向我提供一个有效的示例或指导我针对xcode s(wift)和phonegap更改代码的内容,我将非常感谢

would really appreciate it if someone can provide me with a working example or guide me on what to change in my code for both an xcode s(wift) and phonegap

Xcode(快速3)

Xcode (Swift 3)

import UIKit
import CoreLocation
import CoreBluetooth

class ViewController: UIViewController,CLLocationManagerDelegate,CBPeripheralManagerDelegate,UITextFieldDelegate{

    var locationManager = CLLocationManager()
    var startLocation: CLLocation!
    var localBeacon: CLBeaconRegion!
    var beaconPeripheralData: NSDictionary!
    var peripheralManager: CBPeripheralManager!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        locationManager.delegate = self

        locationManager.requestAlwaysAuthorization()

        bleSwitch.addTarget(self, action: #selector(ViewController.bleSwitchUpdated(_:)), for: UIControlEvents.valueChanged)

        major.delegate=self
        minor.delegate=self
        txPower.delegate=self

    }

    @IBOutlet weak var minor: UITextField!
    @IBOutlet weak var major: UITextField!
    @IBOutlet weak var txPower: UITextField!
    @IBOutlet weak var bleSwitch: UISwitch!
    @IBOutlet weak var bleView: UIView!
    @IBAction func bleSwitchUpdated(_ sender: UISwitch) {
        if bleSwitch.isOn {
            initLocalBeacon()
            bleView.isHidden = false;
        //bleSwitch.setOn(true, animated: false)
        }
        else {
        stopLocalBeacon()
            bleView.isHidden = true;
        }
    }

    func initLocalBeacon() {
        if localBeacon != nil {
            stopLocalBeacon()
        }

        let localBeaconUUID = "5A4BCFCE-174E-4BAC-A814-092E77F6B7E5"
        let localBeaconMajor: CLBeaconMajorValue = UInt16(major.text!)!
        let localBeaconMinor: CLBeaconMinorValue = UInt16(minor.text!)!

        let uuid = UUID(uuidString: localBeaconUUID)!
        localBeacon = CLBeaconRegion(proximityUUID: uuid, major: localBeaconMajor, minor: localBeaconMinor, identifier: "Your private identifer here")

        beaconPeripheralData = localBeacon.peripheralData(withMeasuredPower: -59)
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
    }

    func stopLocalBeacon() {
        peripheralManager.stopAdvertising()
        peripheralManager = nil
        beaconPeripheralData = nil
        localBeacon = nil
    }

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            peripheralManager.startAdvertising(beaconPeripheralData as! [String: AnyObject]!)
        } else if peripheral.state == .poweredOff {
            peripheralManager.stopAdvertising()
        }
    }

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true

    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
        if bleSwitch.isOn == true{
        stopLocalBeacon()
            initLocalBeacon()
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

Phonegap

    var app = (function()
{

           // Application object.
    var app = {};

    // Background flag.
    var mAppInBackground = false;

        app.initialize = function()
    {
        document.addEventListener('deviceready', onDeviceReady, false);
        document.addEventListener('pause', onAppToBackground, false);
        document.addEventListener('resume', onAppToForeground, false);
    };

    function onDeviceReady()
    {
        startMonitoringAndRanging();
        startNearestBeaconDisplayTimer();
        displayRegionEvents();

    }

    function onAppToBackground()
    {
        mAppInBackground = true;
        stopNearestBeaconDisplayTimer();
    }

    function onAppToForeground()
    {
        mAppInBackground = false;
        startNearestBeaconDisplayTimer();
        displayRegionEvents();
    }


    function startMonitoringAndRanging()
    {

        // Request permission from user to access location info.
        cordova.plugins.locationManager.requestAlwaysAuthorization();

           BleconOn();

    }


           function BleconOn(){
           var uuid = '00000000-0000-0000-0000-000000000000';
           var identifier = 'advertisedBeacon';
           var minor = 2000;
           var major = 5;
           var beaconRegion = new cordova.plugins.locationManager.BeaconRegion(identifier, uuid, major, minor);

           var delegate = new cordova.plugins.locationManager.Delegate();


           delegate.peripheralManagerDidStartAdvertising = function(pluginResult) {
           console.log('peripheralManagerDidStartAdvertising: '+ JSON.stringify(pluginResult.region));
           };
           // Event when bluetooth transmission state changes
           // If 'state' is not set to BluetoothManagerStatePoweredOn when advertising cannot start
           delegate.peripheralManagerDidUpdateState = function(pluginResult) {
           console.log('peripheralManagerDidUpdateState: '+ pluginResult.state);
           };

           cordova.plugins.locationManager.setDelegate(delegate);

           // Verify the platform supports transmitting as a beacon
           cordova.plugins.locationManager.isAdvertisingAvailable()
           .then(function(isSupported){

                 if (isSupported) {
                 cordova.plugins.locationManager.startAdvertising(beaconRegion)
                 .fail(conole.error)
                 .done();
                 } else {
                 console.log("Advertising not supported");
                 }
                 })
           .fail(function(e) { console.error(e); })
           .done();
           }

           function BleconOff(){

           cordova.plugins.locationManager.stopAdvertising()
           .fail(console.error)
           .done();
           }



    return app;

})();

app.initialize();

对于这两个代码,都在目标的后台功能中检查了位置更新和后台获取.另外,两个播放列表上都添加了隐私-始终使用位置描述"

for both codes , the location updates and background fetch are checked in the background capabilities for the target. Also , Privacy - Location Always Usage Description is added on both playlists

推荐答案

不幸的是,Apple在iOS的后台阻止了作为信标传输的功能.实际上,所有CoreBluetooth标准广告都被阻止了,因为广告位是一种有限的资源,在后台使用多个应用程序会很快耗尽该资源.

Unfortunately, Apple blocks the ability to transmit as a beacon in the background on iOS. All CoreBluetooth standard advertisements are actually blocked, because advertising slots are a limited resource and multiple apps in the background would exhaust this resource quickly.

Apple确实有一个专有的备份系统,用于在后台播发蓝牙服务,该系统使用特殊的溢出区域来包含服务标识符.但是,尽管该方案适用于在后台广播蓝牙服务,但不适用于广告信标,因为它破坏了格式.

Apple does have a proprietary backup system for advertising Bluetooth services in the background that uses a special overflow area to include the service identifiers. But while this scheme works for advertising Bluetooth services in the background, it does not work for advertising beacons, because it breaks the format.

底线:iOS上的背景信标广告不起作用.抱歉.

Bottom line: background beacon advertising on iOS just does not work. Sorry.

这篇关于如何在xcode(swift)和phonegap中在后台将iPhone作为信标运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆