parse-repository-header-sdk-swift

iOS · macOS · watchOS · tvOS · Linux · Android · Windows


Build Status CI Build Status Release Coverage Carthage Pod

Swift Versions Platforms

Backers on Open Collective Sponsors on Open Collective License Forum Twitter


一个纯 Swift 库,让你可以从你的 Swift 应用程序访问强大的 Parse Server 后端。

有关 Parse 平台及其功能的更多信息,请参阅公共文档。ParseSwift SDK 不是 Parse-SDK-iOS-OSX SDK 的端口,虽然其中一些内容可能看起来很熟悉,但它不向后兼容,并且使用面向协议的编程 (POP) 和值类型而不是 OOP 和引用类型进行设计。 您可以通过观看 Swift 中的面向协议的编程UIKit 应用程序中的协议和面向值的编程 WWDC 的视频来了解有关 POP 的更多信息。 有关 ParseSwift 的更多详细信息,请访问 api 文档

要学习如何使用或实验 ParseSwift,您可以运行和编辑 ParseSwift.playground。 你可以使用 这个 repo 中的 parse-server,它有 docker compose 文件(docker-compose up 给你一个工作服务器),配置为连接到 playground 文件,有 Parse Dashboard,并且可以与 MongoDB 或 PostgreSQL 一起使用。 您还可以通过编辑 Common.swift 中的配置,来配置 Swift Playgrounds 以使用您自己的 Parse Server。 要了解更多信息,请查看 CONTRIBUTING.md


安装

Swift Package Manager

您可以使用 Swift Package Manager (SPM) 通过将以下描述添加到您的 Package.swift 文件中来安装 ParseSwift

// swift-tools-version:5.5
import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/parse-community/Parse-Swift", .upToNextMajor(from: "4.0.0")),
    ]
)

然后运行 swift build

您也可以在您的 Xcode 项目中使用 SPM 安装,方法是转到 “Project->NameOfYourProject->Swift Packages” 并在搜索字段中放置 https://github.com/parse-community/Parse-Swift.git

CocoaPods

将以下行添加到您的 Podfile

pod 'ParseSwift'

运行 pod install,您现在应该拥有来自 main 分支的最新版本。

Carthage

将以下行添加到您的 Cartfile

github "parse-community/Parse-Swift"

运行 carthage update,您现在应该在您的 Carthage 文件夹中拥有最新版本的 ParseSwift SDK。

使用指南

安装 ParseSwift 后,要使用它,首先在您的 AppDelegate.swift 中 import ParseSwift,然后在您的 application:didFinishLaunchingWithOptions: 方法中添加以下代码

ParseSwift.initialize(applicationId: "xxxxxxxxxx", clientKey: "xxxxxxxxxx", serverURL: URL(string: "https://example.com")!)

请查看 Swift Playground 以获取更多使用信息。

LiveQuery

Query 是 Parse 平台上的关键概念之一。 它允许您通过指定一些条件来检索 ParseObject,从而轻松构建仪表板、待办事项列表甚至一些策略游戏等应用程序。 但是,Query 基于拉取模型,不适合需要实时支持的应用程序。

假设您正在构建一个允许多个用户同时编辑同一文件的应用程序。 Query 不是理想的工具,因为您无法知道何时从服务器查询以获取更新。

为了解决这个问题,我们引入了 Parse LiveQuery。 此工具允许您订阅您感兴趣的 Query。 订阅后,每当创建或更新与 Query 匹配的 ParseObject 时,服务器都会实时通知客户端。

设置服务器

Parse LiveQuery 包含两个部分,LiveQuery 服务器和 LiveQuery 客户端(此 SDK)。 为了使用实时查询,您至少需要设置服务器。

设置 LiveQuery 服务器的最简单方法是使其与开源 Parse Server 一起运行。

使用客户端

使用 Combine 的 SwiftUI 视图模型

LiveQuery 客户端界面围绕 Subscription 的概念构建。 您可以为来自关联的实时查询服务器的实时更新注册任何 Query,并通过简单地使用查询的 subscribe 属性将查询用作 SwiftUI 视图的视图模型

let myQuery = GameScore.query("points" > 9)

struct ContentView: View {

    //: A LiveQuery subscription can be used as a view model in SwiftUI
    @StateObject var subscription = myQuery.subscribe!
    
    var body: some View {
        VStack {

            if subscription.subscribed != nil {
                Text("Subscribed to query!")
            } else if subscription.unsubscribed != nil {
                Text("Unsubscribed from query!")
            } else if let event = subscription.event {

                //: This is how you register to receive notificaitons of events related to your LiveQuery.
                switch event.event {

                case .entered(let object):
                    Text("Entered with points: \(object.points)")
                case .left(let object):
                    Text("Left with points: \(object.points)")
                case .created(let object):
                    Text("Created with points: \(object.points)")
                case .updated(let object):
                    Text("Updated with points: \(object.points)")
                case .deleted(let object):
                    Text("Deleted with points: \(object.points)")
                }
            } else {
                Text("Not subscribed to a query")
            }

            Spacer()

            Text("Update GameScore in Parse Dashboard to see changes here")

            Button(action: {
                try? query.unsubscribe()
            }, label: {
                Text("Unsubscribe")
                    .font(.headline)
                    .background(Color.red)
                    .foregroundColor(.white)
                    .padding()
                    .cornerRadius(20.0)
                    .frame(width: 300, height: 50)
            })
        }
    }
}

或者通过调用查询的 subscribe(_ client: ParseLiveQuery) 方法。 如果您想更自定义您的视图模型,您可以子类化 Subscription 或将订阅添加到您自己的视图模型。 您可以在 Swift Playgrounds 中测试 LiveQuery 订阅。

传统回调

您还可以使用异步回调来订阅 LiveQuery

let myQuery = Message.query("from" == "parse")
guard let subscription = myQuery.subscribeCallback else {
    print("Error subscribing...")
    return
}

或者通过调用查询的 subscribeCallback(_ client: ParseLiveQuery) 方法。

其中 Message 是一个 ParseObject。

一旦您订阅了查询,您就可以 handle 它们上的事件,就像这样

subscription.handleSubscribe { subscribedQuery, isNew in

    //Handle the subscription however you like.
    if isNew {
        print("Successfully subscribed to new query \(subscribedQuery)")
    } else {
        print("Successfully updated subscription to new query \(subscribedQuery)")
    }
}

您可以处理 LiveQuery 规范中列出的任何事件

subscription.handleEvent { _, event in
    // Called whenever an object was created
    switch event {

    case .entered(let object):
        print("Entered: \(object)")
    case .left(let object):
        print("Left: \(object)")
    case .created(let object):
        print("Created: \(object)")
    case .updated(let object):
        print("Updated: \(object)")
    case .deleted(let object):
        print("Deleted: \(object)")
    }
}

类似地,您可以取消订阅并注册以便在发生时收到通知

subscription.handleUnsubscribe { query in
    print("Unsubscribed from \(query)")
}

//: To unsubscribe from your query.
do {
    try query.unsubscribe()
} catch {
    print(error)
}

处理错误和其他事件是类似的,请查看 Subscription 类以获取更多信息。 您可以在 Swift Playgrounds 中测试 LiveQuery 订阅。

高级用法

您不限于单个 Live Query 客户端 - 您可以创建 ParseLiveQuery 的多个实例,使用证书身份验证和 pinning,接收有关每个客户端连接的指标,连接到单个服务器 URL 等等。

从 Parse ObjC SDK 迁移

请参阅迁移指南,以帮助您从 Parse ObjC SDK 迁移。