parse-swift

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

⭐️ ParseSwift 已在 iOS Dev Weekly第 560 期 中重点介绍,并在 Swift Package Index Twitter Spaces第 5 集 中讨论。


Playgrounds Documentation Tutorial ci release Coverage Codacy Badge Pod License Swift Versions Platforms


一个纯 Swift 库,让您可以访问强大的 Parse Server 后端。通过查看功能比较表,了解 ParseSwiftOG 为何优于所有其他 Parse SDK。

ParseSwiftOG SDK 不是 Parse-SDK-iOS-OSX SDK 的移植版本,虽然其中一些内容可能感觉熟悉,但它不向后兼容,并且是使用面向协议编程 (POP)值类型而不是 OOP 和引用类型设计的。您可以通过观看 Swift 中的面向协议编程UIKit 应用程序中的协议和面向值编程 WWDC 的视频来了解更多关于 POP 的信息。有关 ParseSwiftOG 的更多详细信息,请访问 api 文档

ℹ️ 为何选择 ParseSwiftOG 而不是 parse-community/Parse-Swift?
此仓库由 Corey E. Baker 维护,他是 ParseSwift 的两位原始开发者之一。Corey 负责从 1.0.04.14.2 的所有 parse-community 版本的 ParseSwift 的方向和开发。ParseSwiftOG 拥有最新的功能和错误修复,可用于开发客户端和服务器端应用程序。它是迄今为止最灵活的 Parse 客户端 SDK,可用于编写 Cloud Code,并且在开发过程中零依赖。此仓库与 swifty 框架的原始核心原则保持一致。请 Star、Watch 并提交问题issuepull requestNetReconLab ParseSwiftOG,而不是 parse-community ParseSwift,以支持其开发。通过阅读讨论,了解如何无缝地将您的应用程序从 parse-community 迁移到 ParseSwiftOG。有关 ParseSwiftOG 为何存在的更多详细信息,请参阅讨论。如果您从 ParseSwift 中受益并希望给予资金支持,请随时
Buy Me A Coffee

贡献者

奉献时间和精力的开发者使这个仓库成为可能!


示例应用和框架

以下是使用 ParseSwiftOG 的应用和框架列表,以帮助开发者利用该框架

试用 Parse-Swift

要了解如何使用或试验 ParseSwiftOG,您可以运行并编辑 ParseSwift.playground。您可以使用 此仓库 中的 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) 安装 ParseSwiftOG,方法是将以下描述添加到您的 Package.swift 文件中

// swift-tools-version:5.5.2
import PackageDescription

let package = Package(
    name: "YOUR_PROJECT_NAME",
    dependencies: [
        .package(url: "https://github.com/netreconlab/Parse-Swift", .upToNextMajor(from: "5.10.3"))
    ],
    targets: [
        .target(
            name: "YOUR_PROJECT_NAME",
            dependencies: [
                .product(name: "ParseSwift", package: "Parse-Swift")
            ]
        ),
        .testTarget(
            name: "YOUR_PROJECT_NAMETests",
            dependencies: ["YOUR_PROJECT_NAME"]
        )
    ]
)

然后运行 swift build

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

CocoaPods

将以下行添加到您的 Podfile

pod 'ParseSwiftOG'

要链接到 main 分支上的最新更新,请将以下行添加到您的 Podfile

pod 'ParseSwiftOG', :git => 'https://github.com/netreconlab/Parse-Swift.git', :branch => 'main'

在您的项目中,使用

import ParseSwiftOG

使用指南

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

try await 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 视图的视图模型

//: 像往常一样创建一个查询。
var query = GameScore.query("points" < 11)
//: 在 SwiftUI 中使用订阅
struct ContentView: View {
//: LiveQuery 订阅可以用作 SwiftUI 中的视图模型
@StateObject var subscription: Subscription<GameScore>
var body: some View {
VStack {
if subscription.isSubscribed {
Text("Subscribed to query!")
} else if subscription.isUnsubscribed {
Text("Unsubscribed from query!")
} else if let event = subscription.event {
//: 这是您注册接收与您的 LiveQuery 相关的事件通知的方式。
switch event.event {
case .entered(let object):
Text("Entered with points: \(String(describing: object.points))")
case .left(let object):
Text("Left with points: \(String(describing: object.points))")
case .created(let object):
Text("Created with points: \(String(describing: object.points))")
case .updated(let object):
Text("Updated with points: \(String(describing: object.points))")
case .deleted(let object):
Text("Deleted with points: \(String(describing: object.points))")
}
} else {
Text("Not subscribed to a query")
}
Text("Update GameScore in Parse Dashboard to see changes here:")
Button(action: {
Task {
try? await query.unsubscribe()
}
}, label: {
Text("Unsubscribe")
.font(.headline)
.background(Color.red)
.foregroundColor(.white)
.padding()
.cornerRadius(20.0)
})
Spacer()
}
}
}
@MainActor
func startView() async throws {
let subscribe = try await query.subscribe()
PlaygroundPage.current.setLiveView(ContentView(subscription: subscribe))
}

or by calling the subscribe(_ client: ParseLiveQuery) method of a query. If you want to customize your view model more you can subclass Subscription or add the subscription to your own view model. You can test out LiveQuery subscriptions in Swift Playgrounds.

传统回调

You can also use asynchronous call backs to subscribe to a LiveQuery

let myQuery = Message.query("from" == "parse")
do {
  let subscription = try await myQuery.subscribeCallback()
} catch {
    print("Error subscribing...")
}

or by calling the subscribeCallback(_ client: ParseLiveQuery) method of a query.

Where Message is a ParseObject.

Once you've subscribed to a query, you can handle events on them, like so

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)")
    }
}

You can handle any event for LiveQuery docs

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)")
    }
}

Similiarly, you can unsubscribe and register to be notified when it occurs

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

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

Handling errors is and other events is similar, take a look at the Subscription class for more information. You can test out LiveQuery subscriptions in Swift Playgrounds.

高级用法

You are not limited to a single Live Query Client - you can create multiple instances of ParseLiveQuery, use certificate authentication and pinning, receive metrics about each client connection, connect to individual server URLs, and more.

从旧版本和 SDK 迁移

  1. See the discussion to learn how to migrate from ParseSwiftOG 4.15.0+ to 5.1.1+
  2. See the discussion to learn how to migrate from parse-community/Parse-Swift
  3. See the discussion to learn how to migrate from Parse-SDK-iOS-OSX