一个简单且强大的方式来交互 iOS 和 macOS 的 VK API。
关键特性
目录
需求
- Swift 4.0+
- iOS 8.0+
- macOS 10.10+
- Xcode 9.0+
集成
Carthage (推荐)
github "SwiftyVK/SwiftyVK"
CocoaPods
use_frameworks!
target '$MySuperApp$' do
pod 'SwiftyVK'
end
手动
- 只需将 SwiftyVK.framework 或整个 SwiftyVK.xcodeproj 拖拽到项目中即可
- 在与应用链接时,在 您的目标首选项 -> 通用 -> 嵌入式可执行文件 中连接 SwiftyVK.framework
入门指南
实现SwiftyVKDelegate
要开始使用SwiftyVK
,你应该在你的自定义VKDelegate
类中实现SwiftyVKDelegate
协议。它用于通知您的应用程序有关重要的SwiftyVK生命周期事件。
例如
import SwiftyVK
class VKDelegateExample: SwiftyVKDelegate {
func vkNeedsScopes(for sessionId: String) -> Scopes {
// Called when SwiftyVK attempts to get access to user account
// Should return a set of permission scopes
}
func vkNeedToPresent(viewController: VKViewController) {
// Called when SwiftyVK wants to present UI (e.g. webView or captcha)
// Should display given view controller from current top view controller
}
func vkTokenCreated(for sessionId: String, info: [String : String]) {
// Called when user grants access and SwiftyVK gets new session token
// Can be used to run SwiftyVK requests and save session data
}
func vkTokenUpdated(for sessionId: String, info: [String : String]) {
// Called when existing session token has expired and successfully refreshed
// You don't need to do anything special here
}
func vkTokenRemoved(for sessionId: String) {
// Called when user was logged out
// Use this method to cancel all SwiftyVK requests and remove session data
}
}
查看示例项目中的完整实现
设置 VK 应用程序
- 创建新的独立应用程序
- 保存
应用程序标识符
,从 设置 -> 应用程序标识符 中获取 - 使用前一步骤获取的
应用程序标识符
和VKDelegate
设置 SwiftyVK
VK.setUp(appId: String, delegate: SwiftyVKDelegate)
发布
为了释放SwiftyVK使用占用的资源
VK.release()
注意,您必须重新设置才能继续使用
授权
SwiftyVK 提供了多种用户授权方式。请选择最合适您的一种。
OAuth WebView
这是一种标准的授权方法,它显示带有OAuth对话框的网页视图。适用于大多数情况。
VK.sessions.default.logIn(
onSuccess: { _ in
// Start working with SwiftyVK session here
},
onError: { _ in
// Handle an error if something went wrong
}
)
官方 VK 应用
如果用户已在设备上安装了官方 VK 应用,则可以使用 SwiftyVK 通过它进行授权。为此
-
在 Xcode -> Target -> Info -> URL 类型
- 添加新的 URL 类型如
vk$YOUR_APP_ID$
(例如,vk1234567890) - 将应用架构添加到 Info.plist 文件
- 添加新的 URL 类型如
<key>LSApplicationQueriesSchemes</key>
<array>
<string>vkauthorize</string>
<string>vk$YOUR_APP_ID$</string>
</array>
-
从 Xcode -> $App Target$ -> General -> Bundle Identifier 复制
Application Bundle
(例如,com.developer.applicationName) -
将复制的
Application Bundle
设置为 https://vk.com/apps?act=manage -> 编辑应用 -> 设置 -> iOS 的应用捆绑 ID 字段 -
将以下代码添加到 AppDelegate
- 对于 iOS 9 及以下版本
func application(
_ application: UIApplication,
open url: URL,
sourceApplication: String?,
annotation: Any
) -> Bool {
VK.handle(url: url, sourceApplication: sourceApplication)
return true
}
- 对于 iOS 10 及以上版本
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]
) -> Bool {
let app = options[.sourceApplication] as? String
VK.handle(url: url, sourceApplication: app)
return true
}
-
按 oAuth WebView 中所述进行授权。
如果用户在 VK 应用中拒绝授权,SwiftyVK 将显示 oAuth 对话框
原始令牌字符串
如果您之前收到过用户令牌,只需将其传递给以下方法
VK.sessions.default.logIn(rawToken: String, expires: TimeInterval)
// Start working with SwiftyVK session here
TimeInterval
是一个时间,在此时间后令牌将不再有效。如果想让令牌永远不过期,则传递 0
。
与 VK API 的交互
SwiftyVK 为与 VK API 的交互提供了非常简单的接口。所有请求都由 API 调度器异步执行(默认情况下,调度器每秒最多发送 3 个请求)在私有队列中。您只需发送请求即可获得回应,无需很多工作。
所有 API 方法都列在这里这里
让我们更深入地看看请求语法
请求
基本请求调用看起来像 VK.methodGroup.methodName()。
例如,要获取当前用户的基本信息
VK.API.Users.get(.empty)
.onSuccess { /* handle and parse response */ }
.onError { /* handle error */ }
.send()
使用以下方式创建的对象
VK.API.Users.get(.empty)
表示一个可以立即发送或先配置后稍后发送的请求。
参数
如果你想在之前示例中获取用户Additional fields,你可以设置请求参数。
VK.API.Users.get([
.userId: "1",
.fields: "sex,bdate,city"
])
如果不需要传递任何参数,请使用.empty
。
回调
请求异步执行,并提供一些回调来处理执行结果
onSuccess
该回调将在请求成功并返回 Data
对象时被调用。您可以使用任何 JSON 解析方法(例如 JSONSerialization
、Codable
、SwiftyJSON 以及其他方法)处理和解析响应。
VK.API.Users.get(.empty)
.onSuccess {
let response = try JSONSerialization.jsonObject(with: $0)
}
您可以在 onSuccess
回调中抛出错误,这将导致 onError
被调用并传递您的错误。
onError
此回调将在请求因某些原因失败时被调用。您可以在该回调中处理抛出的错误。
VK.API.Users.get(.empty)
.onError {
print("Request failed with error: ($0)")
}
取消
如果你不再需要发送计划请求(例如,屏幕弹出),只需取消即可
// `send()` function returns `Task` object which has `cancel()` function
let request = VK.API.Users.get([
.userId: "1",
.fields: "sex,bdate,city"
])
.onSuccess { print($0) }
.send()
// Cancel sheduled request.
// onSuccess callback will never be executed.
request.cancel()
链式调用
SwiftyVK 允许你链式调用请求。如果你的第二个请求需要消耗第一个请求的响应,只需将它们连在一起即可
VK.API.Users.get(.empty)
.chain { response in
// This block will be called only
// when `users.get` method is successfully executed.
// Receives result of executing `users.get` method.
let user = try JSONDecoder().decode(User.self, from: response)
return VK.API.Messages.send([
.userId: user.id,
.message: "Hello"
])
}
.onSuccess { response in
// This block will be called only when both `users.get` and `messages.send`
// methods are successfully executed.
// `response` is a result of `messages.send` method
}
.onError { error in
// This block will be called when either `users.get` or `messages.send` methods is failed.
// Receives error of executing `users.get` or `messages.send` method.
}
.send()
使用 SwiftyVK,你可以创建非常长的链!
配置
在SwiftyVK中,每个session都会为其请求设置默认配置。每个请求都会从其session获取配置。配置包含如下设置:httpMethod
、attemptTimeout
以及其他设置。
你可以为单个请求
// Set different httpMethod only for this request
VK.API.Users.get(.empty)
.configure(with: Config(httpMethod: .POST))
或整个session更改配置
// Set default apiVersion value for all requests in default session
VK.sessions.default.config.apiVersion = "5.68"
你可以更改以下配置属性
属性 | 默认值 | 描述 |
---|---|---|
httpMethod |
.GET |
HTTP方法。你可以使用GET 或POST 。对于大体积数据(例如message.send 方法中的长消息文本),请使用POST 方法。 |
apiVersion |
最新版本 |
VK API版本。默认使用最新版本。如果需要不同的版本,请更改此值。 |
language |
用户系统语言 |
响应语言。对于EN Pavel Durov ,对于RU Павел Дуров 。 |
attemptsMaxLimit |
3 |
发送请求前允许的最大尝试次数,失败后返回错误。 |
attemptTimeout |
10 |
等待响应的最大超时时间(秒),超过后返回错误。 |
handleErrors |
true |
允许自动处理特定VK错误,当需要授权、验证码解析或验证时,向用户提供对话框。 |
上传文件
SwiftyVK提供了轻松上传文件到VK服务器的功能。例如
// Get path to image file
guard let path = Bundle.main.path(forResource: "testImage", ofType: "jpg") else { return }
// Get data from image file by path
guard let data = try Data(contentsOf: URL(fileURLWithPath: path)) else { return }
// Create SwiftyVK Media representation from given data
let media = Media.image(data: data, type: .jpg)
// Upload image to server
VK.API.Upload.Photo.toWall(media, to: .user(id: "4680178"))
.onSuccess { print($0) }
.onError { print($0) }
.onProgress {
// This callback available only for uploading requests
// Use it to handle uploading status and show it to user
switch $0 {
case let .sent(current, of):
print("sent", current, "of": of)
case let .recieve(current, of):
print("recieve", current, "of": of)
}
}
.send()
一些上传请求不会立即下载文件
例如 VK.API.Upload.Photo.toMessage
将返回 photoId
,您可以在 messages.send
方法中使用它。更多信息见文档。
长轮询交互
启动 LongPoll
使用 SwiftyVK 可以非常容易地与 VK LongPoll 服务器进行交互。只需调用
VK.sessions.default.longPoll.start {
// This callback will be executed each time
// long poll client receives a set of new events
print($0)
}
处理更新
数据格式在此处描述。LongPollEvent 是一个枚举,每个情况下都有关联的 Data
类型值。您可以使用您最喜欢的解析器将其解析为 JSON,例如
VK.sessions.default.longPoll.start {
for event in $0 {
switch event {
case let .type1(data):
let json = JSON(data)
print(json)
default:
break
}
}
}
LongPollEvent 有两个特殊的情况
.forcedStop
- 当 LongPoll 遇到意外错误并停止时返回。您可以再次重新启动。
.historyMayBeLost
- 当 LongPoll 因服务器断开连接很长时间,并且 lpKey
或 timestamp
已过时时返回。您无需手动重新连接 LongPoll,客户端会自动完成。根据此情况,刷新在断网期间可能已更新的数据。
停止长轮询
如果您不再需要接收长轮询更新,只需调用此函数
VK.sessions.default.longPoll.stop()
分享对话框
使用SwiftyVK可以将动态发布到用户墙。为此,您需要
- 实现SwiftyVKDelegate
- 设置VK应用程序
- 以上下文呈现分享对话框
VK.sessions.default.share(
ShareContext(
text: "This post made with #SwiftyVK 🖖🏽",
images: [
ShareImage(data: data, type: .jpg), // JPG image representation
],
link: ShareLink(
title: "Follow the white rabbit", // Link description
url: link // URL to site
)
),
onSuccess: { /* Handle response */ },
onError: { /* Handle error */ }
图片和链接为可选,文本是必需的 在macOS 10.10上不支持分享。如果您想使用它,请为此仓库提交一个pull request。
常见问题
许可证
SwifyVK 采用MIT许可证发布。查看LICENSE以获取详细信息。