NoticeObserveKit is type-safe NotificationCenter wrapper.

Overview

NoticeObserveKit

Version License Carthage compatible Platform

NoticeObserveKit is type-safe NotificationCenter wrapper.

// .keyboardWillShow is a static property.
Notice.Center.default.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)
}

If you define custom object, you need to implement that with NoticeUserInfoDecodable protocol. To confirm this protocol, you must implement init?(info: [AnyHashable : Any]) and func dictionaryRepresentation() -> [AnyHashable : Any].

struct UIKeyboardInfo: NoticeUserInfoDecodable {
    let frame: CGRect
    let animationDuration: TimeInterval
    let animationCurve: UIViewAnimationOptions

    init?(info: [AnyHashable : Any]) {
        guard
            let frame = (info[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,
            let duration = info[UIKeyboardAnimationDurationUserInfoKey] as? TimeInterval,
            let curve = info[UIKeyboardAnimationCurveUserInfoKey] as? UInt
        else {
            return nil
        }
        self.frame = frame
        self.animationDuration = duration
        self.animationCurve = UIViewAnimationOptions(rawValue: curve)
    }
}

Usage for under v0.4.0 is documents/v0_4_0.

Customization

If you can post custom Notification like this.

extension Notice.Names {
    static let navigationControllerDidShow = Notice.Name<NavigationControllerContent>(name: "navigationControllerDidShow")
}

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

You can invalidate manually like this.

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

You can use vi NotificationCenter.

NotificationCenter.default.nok.observe(name: .keyboardWillShow) { keyboardInfo in
    print(keyboardInfo)
}
.invalidated(by: pool)

Sample

import UIKit
import NoticeObserveKit

class ViewController: UIViewController {
    private let searchBar = UISearchBar(frame: .zero)
    private var pool = Notice.ObserverPool()

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

        configureObservers()
    }

    private func configureObservers() {
        Notice.Center.default.observe(name: .keyboardWillShow) {
            print("UIKeyboard will show = \($0)")
        }.invalidated(by: pool)

        Notice.Center.default.observe(name: .keyboardWillHide) {
            print("UIKeyboard will hide = \($0)")
        }.invalidated(by: pool)
    }
}

Requirements

  • Swift 5
  • Xcode 10.2 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.

You might also like...
📡 Helping you own NotificationCenter in Swift!

Notificationz 📡 Helping you own NotificationCenter Highlights Keep Your Naming Conventions: This library gives you convenient access to NotificationC

NotificationCenter based Lightweight UI / AnyObject binder.
NotificationCenter based Lightweight UI / AnyObject binder.

Continuum NotificationCenter based Lightweight UI / AnyObject binder. final class ViewController: UIViewController { @IBOutlet weak var label: UI

📡 Helping you own NotificationCenter in Swift!

Notificationz 📡 Helping you own NotificationCenter Highlights Keep Your Naming Conventions: This library gives you convenient access to NotificationC

Swift UIKit E-Commerce (UgurShopping)  No StoryBoard   Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter
Swift UIKit E-Commerce (UgurShopping) No StoryBoard Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter

Swift UIKit E-Commerce (UgurShopping) No StoryBoard Firebase, FireStore, FirebaseAuth, KingFisher, SwiftEntryKit, ProgressHud, Alamofire UICollectionViewCompositionalLayout, NotificationCenter

Simple Interface Core Animation. Run type-safe animation sequencially or parallelly
Simple Interface Core Animation. Run type-safe animation sequencially or parallelly

Simple Interface Core Animation Sica can execute various animations sequentially or parallelly. Features Animation with duration and delay parallel /

Straightforward, type-safe argument parsing for Swift

Swift Argument Parser Usage Begin by declaring a type that defines the information that you need to collect from the command line. Decorate each store

QueryKit, a simple type-safe Core Data query language.
QueryKit, a simple type-safe Core Data query language.

QueryKit QueryKit, a simple type-safe Core Data query language. Usage QuerySetPerson(context, "Person")

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend
Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend

Argo is a library that lets you extract models from JSON or similar structures in a way that's concise, type-safe, and easy to extend. Using Argo

Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift.

Himotoki Himotoki (紐解き) is a type-safe JSON decoding library written purely in Swift. This library is highly inspired by the popular Swift JSON parsin

🕰 Type-safe time calculations in Swift

Time This micro-library is made for you if: You have ever written something like this: let interval: TimeInterval = 10 * 60 To represent 10 minutes. U

Type-safe event handling for Swift

emitter-kit v5.2.2 A replacement for NSNotificationCenter#addObserver and NSObject#addObserver that is type-safe and not verbose. import EmitterKit /

TopicEventBus is Easy to use, type safe way of implementing Publish–subscribe design pattern.
TopicEventBus is Easy to use, type safe way of implementing Publish–subscribe design pattern.

TopicEventBus Publish–subscribe design pattern implementation framework, with ability to publish events by topic. (NotificationCenter extended alterna

A type-safe, high-level networking solution for Swift apps
A type-safe, high-level networking solution for Swift apps

What Type-safe network calls made easy Netswift offers an easy way to perform network calls in a structured and type-safe way. Why Networking in Swift

Protocol oriented, type safe, scalable design system foundation swift framework for iOS.
Protocol oriented, type safe, scalable design system foundation swift framework for iOS.

Doric: Design System Foundation Design System foundation written in Swift. Protocol oriented, type safe, scalable framework for iOS. Features Requirem

Type-Safe Associated Objects in Swift

Type-Safe Associated Objects in Swift TSAO is an implementation of type-safe associated objects in Swift. Objective-C associated objects are useful, b

Easy and type-safe iOS table and collection views in Swift.
Easy and type-safe iOS table and collection views in Swift.

Quick Start TL;DR? SimpleSource is a library that lets you populate and update table views and collection views with ease. It gives you fully typed cl

 SQLite.swift - A type-safe, Swift-language layer over SQLite3.
SQLite.swift - A type-safe, Swift-language layer over SQLite3.

SQLite.swift provides compile-time confidence in SQL statement syntax and intent.

SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.
SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.

SwiftGen is a tool to automatically generate Swift code for resources of your projects (like images, localised strings, etc), to make them type-safe to use.

🌳 Environment – a nicer, type-safe way of working with environment variables in Swift.

🌳 Environment Welcome to Environment – a nicer, type-safe way of working with environment variables in Swift. Usage Access Environment Variables The

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

    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.

    opened by lingfengmarskey 0
Releases(0.12.0)
Owner
Taiki Suzuki
AbemaTV / University of Aizu 18th
Taiki Suzuki
NotificationCenter based Lightweight UI / AnyObject binder.

Continuum NotificationCenter based Lightweight UI / AnyObject binder. final class ViewController: UIViewController { @IBOutlet weak var label: UI

Taiki Suzuki 82 Apr 4, 2021
NoticeObserveKit is type-safe NotificationCenter wrapper.

NoticeObserveKit NoticeObserveKit is type-safe NotificationCenter wrapper. // .keyboardWillShow is a static property. Notice.Center.default.observe(na

Taiki Suzuki 147 Nov 24, 2022
A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety

A Protocol-Oriented NotificationCenter which is type safe, thread safe and with memory safety. Type Safe No more userInfo dictionary and Downcasting,

null 632 Dec 7, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
Type-safe CAAnimation wrapper. It makes preventing to set wrong type values.

TheAnimation TheAnimation is Type-safe CAAnimation wrapper. Introduction For example, if you want to animate backgroundColor with CABasicAnimation, yo

Taiki Suzuki 222 Dec 6, 2022
MemoryCache - type-safe, thread-safe memory cache class in Swift

MemoryCache is a memory cache class in swift. The MemoryCache class incorporates LRU policies, which ensure that a cache doesn’t

Yusuke Morishita 74 Nov 24, 2022
Modern thread-safe and type-safe key-value observing for Swift and Objective-C

Now Archived and Forked PMKVObserver will not be maintained in this repository going forward. Please use, create issues on, and make PRs to the fork o

Postmates Inc. 708 Jun 29, 2022
A phantom type is a custom type that has one or more unused type parameters.

PhantomTypes A phantom type is a custom type that has one or more unused type parameters. Phantom types allow you to enforce type-safety without sacri

null 3 Nov 4, 2022
A type-safe swifty wrapper around NSCache.

swift-cache A type-safe swifty wrapper around NSCache. Getting Started Add swift-cache as a dependency to your project using SPM. .package(url: "https

Binary Scraping 2 Jun 3, 2022
A type-safe auto-generated Swift wrapper around fluentui-emoji

fluentui-emoji.swift A type-safe auto-generated Swift wrapper around fluentui-emoji. Usage Requirements iOS 13+ macOS 10.15+ tvOS 13+ watchOS 6+ Insta

Yubo Qin 11 Dec 27, 2022