• Stars
    star
    3,219
  • Rank 13,949 (Top 0.3 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

⛵️ Elegant URL Routing for Swift

URLNavigator

Swift CocoaPods Build Status CodeCov

⛵️ URLNavigator provides an elegant way to navigate through view controllers by URLs. URL patterns can be mapped by using URLNavigator.register(_:_:) function.

URLNavigator can be used for mapping URL patterns with 2 kind of types: URLNavigable and URLOpenHandler. URLNavigable is a type which defines an custom initializer and URLOpenHandler is a closure which can be executed. Both an initializer and a closure receive an URL and placeholder values.

Getting Started

1. Understanding URL Patterns

URL patterns can contain placeholders. Placeholders will be replaced with matching values from URLs. Use < and > to make placeholders. Placeholders can have types: string(default), int, float, and path.

For example, myapp://user/<int:id> matches with:

  • myapp://user/123
  • myapp://user/87

But it doesn't match with:

  • myapp://user/devxoul (expected int)
  • myapp://user/123/posts (different url structure)
  • /user/devxoul (missing scheme)

2. Mapping View Controllers and URL Open Handlers

URLNavigator allows to map view controllers and URL open handlers with URL patterns. Here's an example of mapping URL patterns with view controllers and a closure. Each closures has three parameters: url, values and context.

  • url is an URL that is passed from push() and present().
  • values is a dictionary that contains URL placeholder keys and values.
  • context is a dictionary which contains extra values passed from push(), present() or open().
let navigator = Navigator()

// register view controllers
navigator.register("myapp://user/<int:id>") { url, values, context in
  guard let userID = values["id"] as? Int else { return nil }
  return UserViewController(userID: userID)
}
navigator.register("myapp://post/<title>") { url, values, context in
  return storyboard.instantiateViewController(withIdentifier: "PostViewController")
}

// register url open handlers
navigator.handle("myapp://alert") { url, values, context in
  let title = url.queryParameters["title"]
  let message = url.queryParameters["message"]
  presentAlertController(title: title, message: message)
  return true
}

3. Pushing, Presenting and Opening URLs

URLNavigator can push and present view controllers and execute closures with URLs.

Provide the from parameter to push() to specify the navigation controller which the new view controller will be pushed. Similarly, provide the from parameter to present() to specify the view controller which the new view controller will be presented. If the nil is passed, which is a default value, current application's top most view controller will be used to push or present view controllers.

present() takes an extra parameter: wrap. If a UINavigationController class is specified, the new view controller will be wrapped with the class. Default value is nil.

Navigator.push("myapp://user/123")
Navigator.present("myapp://post/54321", wrap: UINavigationController.self)

Navigator.open("myapp://alert?title=Hello&message=World")

Installation

URLNavigator officially supports CocoaPods only.

Podfile

pod 'URLNavigator'

Example

You can find an example app here.

  1. Build and install the example app.
  2. Open Safari app
  3. Enter navigator://user/devxoul in the URL bar.
  4. The example app will be launched.

Tips and Tricks

Where to initialize a Navigator instance

  1. Define as a global constant:

    let navigator = Navigator()
    
    class AppDelegate: UIResponder, UIApplicationDelegate {
      // ...
    }
  2. Register to an IoC container:

    container.register(NavigatorProtocol.self) { _ in Navigator() } // Swinject
    let navigator = container.resolve(NavigatorProtocol.self)!
  3. Inject dependency from a composition root.

Where to Map URLs

I'd prefer using separated URL map file.

struct URLNavigationMap {
  static func initialize(navigator: NavigatorProtocol) {
    navigator.register("myapp://user/<int:id>") { ... }
    navigator.register("myapp://post/<title>") { ... }
    navigator.handle("myapp://alert") { ... }
  }
}

Then call initialize() at AppDelegate's application:didFinishLaunchingWithOptions:.

@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {
  func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    // Navigator
    URLNavigationMap.initialize(navigator: navigator)
    
    // Do something else...
  }
}

Implementing AppDelegate Launch Option URL

It's available to open your app with URLs if custom schemes are registered. In order to navigate to view controllers with URLs, you'll have to implement application:didFinishLaunchingWithOptions: method.

func application(
  _ application: UIApplication,
  didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
  // ...
  if let url = launchOptions?[.url] as? URL {
    if let opened = navigator.open(url)
    if !opened {
      navigator.present(url)
    }
  }
  return true
}

Implementing AppDelegate Open URL Method

You'll might want to implement custom URL open handler. Here's an example of using URLNavigator with other URL open handlers.

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
  // If you're using Facebook SDK
  let fb = FBSDKApplicationDelegate.sharedInstance()
  if fb.application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) {
    return true
  }

  // URLNavigator Handler
  if navigator.open(url) {
    return true
  }

  // URLNavigator View Controller
  if navigator.present(url, wrap: UINavigationController.self) != nil {
    return true
  }

  return false
}

Passing Extra Values when Pushing, Presenting and Opening

let context: [AnyHashable: Any] = [
  "fromViewController": self
]
Navigator.push("myapp://user/10", context: context)
Navigator.present("myapp://user/10", context: context)
Navigator.open("myapp://alert?title=Hi", context: context)

Defining custom URL Value Converters

You can define custom URL Value Converters for URL placeholders.

For example, the placeholder <region> is only allowed for the strings ["us-west-1", "ap-northeast-2", "eu-west-3"]. If it doesn't contain any of these, the URL pattern should not match.

Add a custom value converter to the [String: URLValueConverter] dictionary on your instance of Navigator.

navigator.matcher.valueConverters["region"] = { pathComponents, index in
  let allowedRegions = ["us-west-1", "ap-northeast-2", "eu-west-3"]
  if allowedRegions.contains(pathComponents[index]) {
    return pathComponents[index]
  } else {
    return nil
  }
}

With the code above, for example, myapp://region/<region:_> matches with:

  • myapp://region/us-west-1
  • myapp://region/ap-northeast-2
  • myapp://region/eu-west-3

But it doesn't match with:

  • myapp://region/ca-central-1

For additional information, see the implementation of default URL Value Converters.

License

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

More Repositories

1

Then

✨ Super sweet syntactic sugar for Swift initializers
Swift
4,045
star
2

Toaster

🍞 Toast for Swift
Swift
1,668
star
3

UITextView-Placeholder

A missing placeholder for UITextView
Objective-C
1,458
star
4

RxTodo

iOS Todo Application using RxSwift and ReactorKit
Swift
1,291
star
5

SwiftyImage

🎨 Generate image resources in Swift
Swift
1,075
star
6

SwiftUITodo

An example to-do list app using SwiftUI which is introduced in WWDC19
Swift
715
star
7

Umbrella

☂️ Analytics abstraction layer for Swift
Swift
607
star
8

Drrrible

Dribbble for iOS using ReactorKit
Swift
514
star
9

Pure

Pure DI in Swift
Swift
366
star
10

CocoaSeeds

Git Submodule Alternative for Cocoa.
Ruby
341
star
11

RxViewController

RxSwift wrapper for UIViewController and NSViewController
Swift
331
star
12

SwipeBack

Enable iOS 7+ swipe-to-back when custom back button is set.
Objective-C
321
star
13

UICollectionViewFlexLayout

A drop-in replacement for UICollectionViewFlowLayout
Swift
296
star
14

MoyaSugar

🍯 Syntactic sugar for Moya
Swift
191
star
15

Carte

🍴 Open source license notice view generator for Swift
Ruby
189
star
16

graygram-ios

[40시간만에 Swift로 iOS 앱 만들기] 흑백 사진 전용 소셜 미디어 앱
Swift
180
star
17

ReusableKit

Generic reusables for UICollectionView and UITableView
Swift
158
star
18

UINavigationItem-Margin

Margins for UINavigationItem
Objective-C
158
star
19

allkdic

올ㅋ사전 - 맥에서 단축키를 누르면 영어사전이 뙇!!!!
Swift
128
star
20

SwiftyColor

🎨 The most sexy way to use colors in Swift.
Swift
120
star
21

RxCodable

RxSwift wrapper for Codable
Swift
113
star
22

RxExpect

RxSwift testing framework
Swift
105
star
23

korail

🚆 An unofficial Korail API for Python.
Python
90
star
24

Stubber

A minimal method stub for Swift
Swift
86
star
25

Cleverbot

iOS Messaging Application using Cleverbot and ReactorKit
Swift
78
star
26

Blockchain

A blockchain simulator written in Swift
Swift
65
star
27

LetsGitHubSearch

Let'Swift 18 Workshop - Let's TDD
Swift
63
star
28

CancelBag

A DisposeBag for Combine
Swift
53
star
29

TouchAreaInsets

Expand UIView touch area just like a charm
Objective-C
50
star
30

UIViewController-NavigationBar

[Deprecated] UIViewController with its own navigation bar. It provides an availability for the smooth push/pop animations between view controllers which have different navigation bar styles.
Swift
50
star
31

ios-with-swift-in-40-hours

40시간만에 Swift로 iOS 앱 하나를 만들어봅시다.
49
star
32

SectionReactor

A ReactorKit extension for managing table view and collection view sections with RxDataSources
Swift
45
star
33

Fallback

💊 Syntactic sugar for Swift do-try-catch
Swift
42
star
34

SafeCollection

Safe Collection for Swift
Swift
42
star
35

AsyncBlockOperation

NSOperation subclass for async block.
Objective-C
41
star
36

CGFloatLiteral

CGFloat(10) becomes 10.f
Swift
35
star
37

Endpoint

🚀 Elegant API Abstraction for Swift
Swift
35
star
38

RxJSON

RxSwift wrapper for JSON
Swift
33
star
39

ASCollectionFlexLayout

A custom collection layout that allows to use Texture layout specs in ASCollectionNode.
Swift
27
star
40

next-route-map

🚏 Routes for Next.js
TypeScript
26
star
41

Date.swift

📅 A Swift Date Library
Swift
26
star
42

ImageEffects

Bring UIImageEffects (WWDC 2013) to UIImage category with handy interface.
Objective-C
25
star
43

Todobox

[40시간만에 Swift로 iOS 앱 만들기] 할 일 목록 관리 애플리케이션
Swift
24
star
44

RxReusable

Reusable cells and views for RxSwift
Swift
23
star
45

AlertReactor

A ReactorKit extension for UIAlertController
Swift
23
star
46

UIButton-BackgroundContentMode

A missing background content mode for UIButton.
Objective-C
22
star
47

sketch-export-sizes-generator

💎 A simple plugin for Sketch that generates export sizes of layers.
20
star
48

RxDelegateCells

[Don't use this] UITableView Cell Height and UICollectionView Cell Size for RxSwift
Swift
19
star
49

Immutable

Missing non-mutating functions in Swift
Swift
18
star
50

PureSwinject

Auto register Pure factories to Swinject
Swift
18
star
51

graygram-web

Python
16
star
52

daumpostcode

다음 우편번호 서비스를 별도의 패키지 설치 없이도 네이티브 앱에서 쉽게 사용할 수 있습니다.
HTML
16
star
53

Swiftproj

A command-line tool for managing Xcode project with Swift Package Manager.
Ruby
15
star
54

Meal

[40시간만에 Swift로 iOS 앱 만들기] 전국 초/중/고등학교 급식 조회 애플리케이션
Swift
15
star
55

SwinjectSafeAuto

SwinjectSafeAuto allows to auto-register services to the container and verify the required services are properly registered.
Swift
14
star
56

FastLogin

2018 FAST CAMPUS DEV SEMINAR 실습 앱
Swift
14
star
57

NSOperationQueue-CompletionBlock

Completion block for NSOperationQueue.
Objective-C
13
star
58

graphql-codegen-typescript-fixtures

A plugin for graphql-code-generator that generates TypeScript fixtures for testing.
TypeScript
12
star
59

Kodium

Better Korean typo for medium.com
JavaScript
11
star
60

Estimator

Planning Poker application that communicates over BLE (Bluetoothe Low Energy)
Swift
10
star
61

Slots

Dynamic contents management for Swift.
Swift
9
star
62

MapViewVisibleAnnotations

Displays which annotations are currently visible in the specific area.
Swift
9
star
63

jira-velocity-chart-completion-rate

Displays completion rate in JIRA velocity chart.
JavaScript
9
star
64

github-monospace-editor

GitHub Monospace Editor Userscript
JavaScript
9
star
65

flask-restdoc

Flask-Restdoc is a simple tool that generates RESTful API documentation automatically from python files.
Python
9
star
66

notion-badge

Embed App Store badge in Notion
HTML
9
star
67

SwinjectFactory

Experimental Swinject extension for factory injection.
Swift
8
star
68

if_

Swift if-else statement as an expression (Experimental)
Swift
8
star
69

flask-errorhandler

Error handlers for Flask blueprints.
Python
7
star
70

shlee322-fb-troll

상혁이의 페북 글마다 일하라는 댓글을 달아보아요 ^오^
Python
7
star
71

adorable

M꙼̈ă̎k̊̈ě̈ t̐̈ȇ̈x̆̈t꙼̈ å̈ď̈ō̈r̐̈ȃ̈b̆̈l꙼̈ĕ̎
HTML
7
star
72

ModelKit

[deprecated] Experimental Model framework for Swift
Swift
7
star
73

resume

My résumé
Makefile
6
star
74

Playground

A playground for an ideal project
HCL
6
star
75

Bagel

GIF converter for Mac
Swift
5
star
76

RxGitHubSearch

An example GitHub search app for my lecture
Swift
5
star
77

xcode-project-template

Swift
5
star
78

staccato

Staccato 모임 소개 페이지
Python
5
star
79

fbmarkdown

Chrome extension that enable markdown on facebook.
JavaScript
5
star
80

JLModel

JLModel allows you to manage models in very simple way.
Objective-C
5
star
81

blog

언젠간 쓰겠지?
CSS
4
star
82

TypedKey

Statically-typed key for Swift.
Swift
4
star
83

devxoul.github.io

HTML
4
star
84

Hippo-iOS

Objective-C
4
star
85

naver-cafe-chat-notification

네이버 카페 새 채팅 개수를 브라우저 타이틀로 알려주는 스크립트.
JavaScript
4
star
86

fabric-verbose

Python
4
star
87

TistoryMarkdown

A Markdown plugin for Tistory.
4
star
88

4SharedDownloader

You can download files from 4shared.com without delay.
ActionScript
4
star
89

help-me-rx-tableview-cell-height

Help me!
Swift
3
star
90

macsafe

Keep your MacBook from thieves.
Python
3
star
91

NAR

Nginx Auto Reloader
JavaScript
2
star
92

Editag

The easiest way to edit id3 tag.
ActionScript
2
star
93

ImageCrawler

JavaScript
2
star
94

ovenbreak

Utils for ovenapp.io
Makefile
2
star
95

JLChromeTabController

A chrome-like tab bar for iOS.
Objective-C
2
star
96

Evermind

Evermind is a handy tool that makes it easy to mindmap your idea from your work, study, and everyday life.
ActionScript
2
star
97

JLUtils

Objective-C
1
star
98

FastcampusFrame

Swift
1
star
99

Sonaki

Objective-C
1
star
100

Calendar

Infinite-scrolling calendar example
Objective-C
1
star