본문 바로가기

iOS

[Swift] NotificationCenter

반응형

데이터를 보내는 방법 여러가지가 있지만 아래가 가장 간단했다.

특히 pop up 을 띄울 경우, 이전 뷰컨으로 보낼때 유용했다.

//button section
NotificationCenter.default.post(name: .writeCharacteristic, object: self.savedTextField)

//initial section(viewDidLoad)
NotificationCenter.default.addObserver(self, selector: #selector(writeCharacteristic), name: .writeCharacteristic, object: nil)

//received data section
@objc func writeCharacteristic(_ notification: Notification) {
    if let text = notification.object as? String {

        var result = [String]()
        for index in (0 ..< text.count) {
            if index%2 == 0 {
                result.append(text.substring(from: index, to: index + 1))
            }
        }

        let intArray: [UInt8] = result.map { UInt8($0, radix: 16)! }
        for index in intArray {
            print("_hyeon intArray[\(index)]: ", index)
        }

        devicePeripheral.writeValue(Data(intArray), for: tvData[writeButtonTag/100].characteristicId[writeButtonTag%100-1], type: .withoutResponse)
    }
}

'iOS' 카테고리의 다른 글

[Swift] contentView  (0) 2022.01.24
[Swift] isUserInteractionEnabled  (0) 2022.01.24
[Swift] Substring  (0) 2022.01.12
[Swift] characteristic read, write  (0) 2022.01.06
[Swift] contentView - expandable tableView  (0) 2022.01.02