为什么我的委托从未被调用?

Why is my delegate never called?

我正在尝试将我的 iPhone 7 Plus 变成 iBeacon 以进行测试

我正在使用下面的代码,但我的委托从未被调用,所以它不会启动广告

- (IBAction)adminViewBeaconSwitchToggled:(id)sender {

    NSUserDefaults *tillUserDefaults = [NSUserDefaults standardUserDefaults];

    if(_adminViewBeaconSwitch.isOn) {
        [tillUserDefaults setInteger:1 forKey:@"beaconIsOn"];
        if ([NWTillHelper isDebug] == 1) {
            NSLog(@"iBeacon Mode: ON");

            NSUUID *proximityUUID = [[NSUUID alloc] initWithUUIDString:@"39876A4B-43B2-4BE8-9A9C-41BAE913D56A"];

            CLBeaconRegion *beaconRegion = [[ CLBeaconRegion alloc] initWithProximityUUID:proximityUUID identifier:@"me.netwizards.office"];

            _beaconPeripheralData = [beaconRegion peripheralDataWithMeasuredPower:nil];

            _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:nil queue:nil];

            //[peripheralManager startAdvertising:beaconPeripheralData];
        }
    } else {
        [tillUserDefaults setInteger:0 forKey:@"beaconIsOn"];
        if ([NWTillHelper isDebug] == 1) {
            NSLog(@"iBeacon Mode: OFF");
        }
    }
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    NSLog(@"iBeacon update state was triggered");

    switch (peripheral.state) {
        case CBManagerStatePoweredOn:
            NSLog(@"Powered on");
            [peripheral startAdvertising:_beaconPeripheralData];
            break;
        case CBManagerStatePoweredOff:
            NSLog(@"Powered Off");
            [peripheral stopAdvertising];
            break;
        case CBManagerStateUnsupported:
            NSLog(@"Device not supported");
            break;
        default:
            break;
    }
}

如何让它真正开始做广告并确保委托被调用?

这里在初始化CBPeripheralManager的对象时

_peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:nil queue:nil];

您将委托作为 nil 传递,您应该将其作为 self.

传递

所以你更新后的代码应该是

_peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];

此外,在 class 中定义委托 CBPeripheralManagerDelegate