iOS Home Screen Action

by minhnn44
194 views

Overview

Khi sử dụng một số ứng dụng phổ biến như Zalo, Telegram hay YouTube, … trên các thiết bị iOS 13 trở lên, hẳn chúng ta đã từng nhìn thấy một số option mới khi long press ở Home Screen như hình dưới. Ở bài viết này, chúng ta sẽ cùng tìm hiểu cách để tạo ra những option đó.

Các option hay shortcut này được gọi là Home Screen Actions (hay Home Screen Quick Actions), được hỗ trợ từ iOS 13 trở lên. Đúng như cái tên của nó, đây là những shortcut được thiết kế để thực hiện trực tiếp lựa chọn các action của ứng dụng tại màn hình Home thay vì phải mở và thao tác nhiều lần bên trong ứng dụng.

Hãy lấy ví dụ như chúng ta có ứng dụng Safari, khi muốn mở Techover trên Safari ta có một số lựa chọn như sau:

  1. Mở Safari -> Tap vào thanh địa chỉ -> Nhập magz.techover.io -> ấn Go
  2. Mở Safari -> Tap New Tab -> Chọn BookMark -> Chọn magz.techover.io

Có thể thấy, để thực hiện công việc trên chúng ta đều cần ít nhất 4 bước, lựa chọn đầu tiên còn yêu cầu người dùng nhập địa chỉ thủ công. Thay vì thế, ta có thể đơn giản hoá bằng cách đưa magz.techover.io vào một shortcut của Safari, chỉ với hai lần chạm, ta đã có thể mở trang web trên Safari một cách nhanh chóng.

Home Screen Action có hai loại, Static và Dynamic:

  1. Static: Luôn cố định, không thể thay đổi tuỳ chỉnh được
  2. Dynamic: Có thể tuỳ chỉnh, thay đổi tuỳ theo hoạt động của ứng dụng

Giờ chúng ta sẽ đi tìm hiểu, làm sao để cấu hình cho từng loại Home Screen Action.

Home Screen Static Action

Đối với Static Actions, chúng ta sẽ cài đặt ở trong Info.plist với cấu trúc sau:

<key>UIApplicationShortcutItems</key>
<array>
    <dict>
        <key>UIApplicationShortcutItemIconType</key>
        <string>UIApplicationShortcutIconTypeHome</string>
        <key>UIApplicationShortcutItemTitle</key>
        <string>Techover</string>
        <key>UIApplicationShortcutItemSubtitle</key>
        <string>Open Techover</string>
        <key>UIApplicationShortcutItemType</key>
        <string>Techover</string>
    </dict>
    <dict>
        <key>UIApplicationShortcutItemIconType</key>
        <string>UIApplicationShortcutIconTypeCompose</string>
        <key>UIApplicationShortcutItemTitle</key>
        <string>New</string>
        <key>UIApplicationShortcutItemSubtitle</key>
        <string>Create New Post</string>
        <key>UIApplicationShortcutItemType</key>
        <string>Create</string>
    </dict>
</array>

Trong đó:

  • Key UIApplicationShortcutItemIconType là define Icon cho Action, các bạn có thể tham khảo list value ở đây
  • Key UIApplicationShortcutItemTitle là define Title cho Action
  • Key UIApplicationShortcutItemSubtitle là define SubTitle, dòng chữ nhỏ phía dưới Title
  • Key UIApplicationShortcutItemType là một String dùng để định danh, phải là duy nhất, dùng để handle xử lý Action ở trong code.

Sau khi setting xong, chúng ta sẽ có kết quả như sau:

Home Screen Dynamic Action

Đối với Dynamic Actions, chúng ta có thể thêm bất cứ chỗ nào bên trong xử lý của ứng dụng bằng đoạn code sau:

let application = UIApplication.shared
var shortcuts = application.shortcutItems
shortcuts?.append(UIApplicationShortcutItem(type: "FavoriteAction",
                                            localizedTitle: "Home Screen Action",
                                            localizedSubtitle: "My first Technopedia post",
                                            icon: UIApplicationShortcutIcon(systemImageName: "star.fill"),
                                            userInfo: ["Marked Post": "Minhnn44-1" as NSSecureCoding]))
shortcuts?.append(UIApplicationShortcutItem(type: "FavoriteAction",
                                            localizedTitle: "iOS Distribution Methods",
                                            localizedSubtitle: "My seconds Technopedia post",
                                            icon: UIApplicationShortcutIcon(systemImageName: "star.fill"),
                                            userInfo: ["Marked Post": "Minhnn44-2" as NSSecureCoding]))
application.shortcutItems = shortcuts

Trong đó, UIApplication.shared.shortcutItems là một [UIApplicationShortcutItem], mỗi một UIApplicationShortcutItem tượng trưng cho một Action ở Home Screen với các tham số khởi tạo:

  • type: String định danh của Action
  • localizedTitle: Title
  • localizedSubtitle: SubTitle
  • icon: icon
  • userInfo: Dictionary để lưu các thông tin cần truyền thêm

Action Handle

Việc handle khi người dùng ấn các action sẽ được thực hiện bên trong SceneDelegate như sau.
Đối với trường hợp ứng dụng chưa được mở (not running), chúng ta sẽ handle bên trong hàm scene(_:willConnectTo:options:) như sau:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    /** Process the quick action if the user selected one to launch the app.
        Grab a reference to the shortcutItem to use in the scene.
    */
    if let shortcutItem = connectionOptions.shortcutItem {
        // Save it off for later when we become active.
        savedShortCutItem = shortcutItem
    }
}

Trong trường hợp ứng dụng đang ở background, chúng ta sẽ handle bên trong hàm windowScene(_:performActionFor:completionHandler:) như sau:

func windowScene(_ windowScene: UIWindowScene,
                 performActionFor shortcutItem: UIApplicationShortcutItem,
                 completionHandler: @escaping (Bool) -> Void) {
    let handled = handleShortCutItem(shortcutItem: shortcutItem)
    completionHandler(handled)
}

func handleShortCutItem(shortcutItem: UIApplicationShortcutItem) -> Bool {
    /** In this sample an alert is being shown to indicate that the action has been triggered,
        but in real code the functionality for the quick action would be triggered.
    */
    switch shortcutItem.type {
    case "Techover":
        print("Techover Selected")
    case "Create":
        print("Create New Post Selected")
    case "FavoriteAction":
        if let markedPost = shortcutItem.userInfo?["Marked Post"] as? String {
            print("Open \(markedPost)")
        }
        break
    default:
        break
    }
    return true
}

Vậy là xong, nếu có thắc mắc hoặc góp ý thì các bạn comment phía dưới để mình giải đáp và cái thiện nhé!

Authors

MinhNN44

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like