2017-02-06 2 views
0

신속한 응용 프로그램을 블루투스 저에너지 주변 장치에 연결합니다. 나는 Swift에서 매우 새롭고 나의 문제는 완전히 BLE가 아닌 신속한 코딩과 관련이있다.제약 조건을 위반하여 복구를 시도합니다. <NSLayoutConstraint : 0x17008b130 UILabel

버튼을 눌렀는지 확인하기 위해 주변 기기를 청취합니다. 레이블을 정의하고 텍스트를 지정했습니다. 앱이 버튼 누름을 감지하면 라벨 테스트가 변경되기를 원하지만 앱이 다운됩니다.

내 여기에 코드를 볼 수 있습니다

: 말한다

import CoreBluetooth 
import UIKit 

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate { 

    var manager:CBCentralManager! 
    var peripheral:CBPeripheral! 
    @IBOutlet weak var statusLabel: UILabel! 


    let BEAN_NAME = "Security Tag" 
    let BEAN_SCRATCH_UUID = CBUUID(string: "00001C0F-D102-11E1-9B23-000EFB0000A7") 
    let BEAN_SERVICE_UUID = CBUUID(string: "00001c00-d102-11e1-9b23-000efb0000a7") 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     manager = CBCentralManager(delegate: self, queue: nil) 
    } 

    func centralManagerDidUpdateState(_ central:CBCentralManager) { 
     if central.state == CBManagerState.poweredOn { 
      central.scanForPeripherals(withServices: nil, options: nil) 
      debugPrint("Searching ...") 
     } else { 
      debugPrint("Bluetooth not available.") 
     } 
    } 

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { 
     let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? NSString 

     if device?.contains(BEAN_NAME) == true { 
      debugPrint("Found Bean.") 

      self.manager.stopScan() 
      self.peripheral = peripheral 
      self.peripheral.delegate = self 

      manager.connect(peripheral, options: nil) 
     } 
    } 

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { 
     debugPrint("Getting services ...") 
     peripheral.discoverServices(nil) 
    } 

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 
     for service in peripheral.services! { 
      let thisService = service as CBService 

      debugPrint("Service: ", service.uuid) 

      if service.uuid == BEAN_SERVICE_UUID { 
       debugPrint("Using scratch.") 
       peripheral.discoverCharacteristics(nil, for: thisService) 
      } 
     } 
    } 

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 
     debugPrint("Enabling ...") 

     for characteristic in service.characteristics! { 
      let thisCharacteristic = characteristic as CBCharacteristic 

      debugPrint("Characteristic: ", thisCharacteristic.uuid) 

      if thisCharacteristic.uuid == BEAN_SCRATCH_UUID { 
       debugPrint("Set to notify: ", thisCharacteristic.uuid) 

       // Prepare to show data 

       self.peripheral.setNotifyValue(true, for: thisCharacteristic) 
      } 
     } 
    } 

    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) { 
     if characteristic.uuid == BEAN_SCRATCH_UUID { 
      let content = String(data: characteristic.value!, encoding: String.Encoding.utf8) 

      debugPrint("Notified.") 
      self.statusLabel.text = "Your Purchase is Registered." 

     } 
    } 

    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { 
     debugPrint("Disconnected.") 

     central.scanForPeripherals(withServices: nil, options: nil) 

     // Hide respective user interface 
    } 

} 

라인 ". 구매를 등록한다"self.statusLabel.text =을

어디에서 예외가 발생합니까?

는이 오류 내가 얻을 수 있습니다 :

2017-02-06 13:42:19.825869 kevinbletest[2143:695095] [LayoutConstraints] Unable to simultaneously satisfy constraints. 
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
     (1) look at each constraint and try to figure out which you don't expect; 
     (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270 (active)>", 
    "<NSLayoutConstraint:0x17008b770 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.centerX == UIView:0x11dd0c850.centerX (active)>", 
    "<NSLayoutConstraint:0x17008b7c0 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.leading == UIView:0x11dd0c850.leadingMargin + 50 (active)>", 
    "<NSLayoutConstraint:0x17408c3f0 'UIView-Encapsulated-Layout-Width' UIView:0x11dd0c850.width == 375 (active)>" 
) 
    Will attempt to recover by breaking constraint 
    <NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270 (active)>  
    Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger. 
    The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful. 
    fatal error: unexpectedly found nil while unwrapping an Optional value 
    2017-02-06 13:42:25.299886 kevinbletest[2143:695095] fatal error: unexpectedly found nil while unwrapping an Optional value 
    (lldb) 
+1

"치명적인 오류가 발생했습니다 : 선택 값을 래핑하는 동안 예기치 않게 nil이 발견되었습니다"이것은 사용자의 문제입니다. –

+1

나는 당신이 틀린 것을보고 있다고 생각합니다. 제약 조건에 문제가 있습니다. 하지만 그것은 레이아웃에만 영향을 주며 앱을 중단시키지 않아야합니다. @NileshPol이 여기 위에 나와 있듯이, 당신은 값이 'nil'인 것을 풀어 버리려고하는'Optional' 값을 가지고 있습니다. 그러면 앱이 다운됩니다. 제 상태는'statusLabel '이 스토리 보드에 연결되어 있지 않다는 것입니다. –

+1

정확히 말하자면, 질문에 진술 한 바와 같이 (self.statusLabel.text = "yourText") 라인에서 예외가 발생한다는 것은 콘센트가 스토리 보드에 연결되어 있지 않다는 의미입니다. 앱이 충돌하는 곳입니다. –

답변

0

여기에있다 :

<NSLayoutConstraint:0x17008b130 UILabel:0x11dd0cbf0'Waiting for a Purchase Co...'.width == 270 (active)> 

이 NSLayout는 (270)의 폭 레이블을 중심하려고하는 것 같다 및 텍스트보다 크기 때문에 실패 아래에 당신이 그것을 아래로 읽으면 270.

아래에는 실제로 레이블이 없기 때문에 앱이 다운된다고 나와 있습니다.

printf(self.myLabel)을 사용해보십시오.

스토리 보드에 추가하고 viewDidAppear 완료 전에 버튼을 누르면 라벨에 아무 것도 표시되지 않을 수 있습니다.

제약없이 사용해보십시오. 제한을 제거하기 만하면됩니다. + ViewController이로드 될 때까지 기다린 다음 (viewDidAppear)를 클릭하십시오.

제한 때문에가 아닌 옵티 날 값을 래핑하지 않으므로 앱이 다운됩니다.

-1

시도가 시각적 경고를 전달 있는지 확인하기 위해 스토리 보드에있는 라벨에 일부 콘텐츠를 설정할 수 있습니다. 레이블에 특정 너비가 있다고 가정하는 제한 조건을 설정 한 것으로 의심됩니다. 스토리 보드에있는 텍스트 문자열과 다른 텍스트 문자열을 할당 할 때 깨집니다. 이를 해결하려면 제약 조건 값을 변경하여 동적 텍스트 (예 : 최소 자간 (예 : 8px)보다 크거나 같도록 후미 제한을 설정하십시오. 내가 오류를 읽은 내용에서