Coder Social home page Coder Social logo

marty-suzuki / noticeobservekit Goto Github PK

View Code? Open in Web Editor NEW
150.0 5.0 7.0 96 KB

NoticeObserveKit is type-safe NotificationCenter wrapper.

License: MIT License

Swift 90.77% Ruby 6.99% Objective-C 2.23%
notificationcenter type-safe swift ios tvos watchos macos

noticeobservekit's Introduction

NoticeObserveKit

Version License Carthage compatible Platform

NoticeObserveKit is type-safe NotificationCenter wrapper.

Swift Concurrency (since macOS 12.0, iOS 15.0, tvOS 15.0, watchOS 8.0)

Task {
    // .keyboardWillShow is a static property.
    for try await keyboardInfo in NotificationCenter.default.nok.notifications(named: .keyboardWillShow) { 
        // In this case, keyboardInfo is UIKeyboardInfo type.
        // It is inferred from a generic parameter of Notice.Name<Value>.
        print(keyboardInfo)
    }
}

Combine (since macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0)

// .keyboardWillShow is a static property.
NotificationCenter.default.nok.publisher(for: .keyboardWillShow)
    .sink(
        receiveCompletion: { _ in },
        receiveValue: { keyboardInfo in
            // In this case, keyboardInfo is UIKeyboardInfo type.
            // It is inferred from a generic parameter of Notice.Name<Value>.
            print(keyboardInfo)
        }
    )
    .store(in: &cancellables)

NoticeObserveKit original

// .keyboardWillShow is a static property.
NotificationCenter.default.nok.observe(name: .keyboardWillShow) { keyboardInfo in
    // In this case, keyboardInfo is UIKeyboardInfo type.
    // It is inferred from a generic parameter of Notice.Name<Value>.
    print(keyboardInfo)
}
// pool is Notice.ObserverPool.
// If pool is released, Notice.Observes are automatically removed.
.invalidated(by: pool)

Usage

First of all, you need to implement Notice.Name<T> like this. T is type of value in notification.userInfo.

extension Notice.Names {
    static let keyboardWillShow = Notice.Name<UIKeyboardInfo>(
        UIResponder.keyboardWillShowNotification
    ) { userInfo in
        // Implementing decode is only required if you want to use an already defined Notification.Name (e.g. UIResponder.keyboardWillShowNotification).
        guard
            let frame = (userInfo[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = userInfo[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval,
            let curve = userInfo[UIKeyboardAnimationCurveUserInfoKey] as? UInt
        else {
            throw DecodeError()
        }

        return UIKeyboardInfo(
            frame: frame,
            animationDuration: duration,
            animationCurve: UIViewAnimationOptions(rawValue: curve)
        )
    }
}

Customization

If you can post custom Notification like this.

extension Notice.Names {
    // If you define your own custom Notification.Name, no implementation of decode is required.
    static let navigationControllerDidShow = Notice.Name<NavigationControllerContent>(name: "navigationControllerDidShow")
}

let content = NavigationControllerContent(viewController: viewController, animated: animated)
NotificationCenter.default.nok.post(name: .navigationControllerDidShow, value: content)

You can invalidate manually like this.

let observer = NotificationCenter.default.nok.observe(name: .keyboardWillShow) { keyboardInfo in
    print(keyboardInfo)
}
observer.invalidate()

Sample

import UIKit
import NoticeObserveKit

class ViewController: UIViewController {
    private let searchBar = UISearchBar(frame: .zero)
    private lazy var keyboardNotificationTasks: [Task<Void, Error>] = [
        Task {
            for try await value in NotificationCenter.default.nok.notifications(named: .keyboardWillShow) {
                print("UIKeyboard will show = \(value)")
            }
        },
        Task {
            for try await value in NotificationCenter.default.nok.notifications(named: .keyboardWillHide) {
                print("UIKeyboard will hide = \(value)")
            }
        }
    ]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        navigationItem.titleView = searchBar

        configureObservers()
    }

    private func configureObservers() {
        _ = keyboardNotificationTasks
    }
}

Requirements

  • Swift 5
  • Xcode 15.0 or greater
  • iOS 10.0 or greater
  • tvOS 10.0 or greater
  • macOS 10.10 or greater
  • watchOS 3.0 or greater

Installation

CocoaPods

NoticeObserveKit is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "NoticeObserveKit"

Carthage

If you’re using Carthage, simply add NoticeObserveKit to your Cartfile:

github "marty-suzuki/NoticeObserveKit"

Make sure to add NoticeObserveKit.framework to "Linked Frameworks and Libraries" and "copy-frameworks" Build Phases.

Author

marty-suzuki, [email protected]

License

NoticeObserveKit is available under the MIT license. See the LICENSE file for more info.

noticeobservekit's People

Contributors

marty-suzuki avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

noticeobservekit's Issues

Observe callback does not contain posted object, only contain userInfo.

version: 0.12

public func observe<Value: NoticeUserInfoDecodable>(name: Notice.Name<Value>,
                                                        object: Any? = nil,
                                                        queue: OperationQueue? = nil,
                                                        using: @escaping (Value) -> Void) -> Notice.Observer {
        let observer = center.addObserver(forName: name.raw, object: object, queue: queue) { notification in
            guard
                let userInfo = notification.userInfo,
                let value = Value(info: userInfo)
                else {
                    return
            }
            using(value)
        }
        return Notice.Observer(center: center, raw: observer)

Here is the implementation in pods.

received object is abandoned, can not get this from outside.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.