MastodonClient

GitHub

GitHub Workflow Status (branch)

使用指南

此客户端旨在连接到任何 Mastodon 实例并与之交互。

MastodonClient 包含一些便捷方法来创建应用程序(OAuth 客户端)并与 API 交互,但您目前应直接使用 URLSession TargetTypes(因为它们的功能已完善),例如,用于获取您的主时间线。

let request = try MastodonClient.request(
    for: URL(string: "https://mastodon.social")!,
    target: Mastodon.Timelines.home(nil, nil),
    withBearerToken: token
)

let (data, _) = try await session.data(for: request)

let result = try JSONDecoder().decode([Status].self, from: data)

假设您已经拥有一个 OAuth 客户端

let app = App(clientId: "", clientSecret: "")

登录就这么简单

let client = MastodonClient(baseURL: URL(string: "https://mastodon.tld")!)

let app = App(
    clientId: "a1a2a3a4a5",
    clientSecret: "s3cr3t"
)

let response = try await client.getToken(
    app,
    username: "test+account@host.tld",
    password: "pa4w0rd",
    scope: ["read", "write", "follow"]
)

如果登录成功并且您已检索到 AccessToken,您可以自由使用所有其他 API,例如,使用 MastodonClientAuthenticated 来检索您的主时间线,例如:

let client = MastodonClient(baseURL: URL(string: "https://mastodon.tld")!)
    .getAuthenticated(token: token)

let result = try await client.getHomeTimeline()

使用 OAuth 登录

要使用 OAuth 登录,请配置您的应用程序以处理自定义 URL 方案。如果使用应用程序沙盒,请务必启用传出连接。

然后使用以下步骤

    let scopes = ["read", "write", "follow"]; //Define your scopes

    let client = MastodonClient(baseURL: URL(string: urlString)!)
    //Create a client instance for the server URL you want to reach

    do {
        //Create an application definition, including your custom URI, and register it with the server:
        guard let app = try await client.createApp(named: "Your App Name", redirectUri: "your-url-scheme://", scopes: scopes, website: URL(string: "https://your-url")!) else {
            return
        }

        let response = try await client.authenticate(app: app, scope: scopes )
        //Trigger the authentication flow
        
        let token = response?.oauthToken as? MastodonSwift.Token
        //Capture the auth token
        
        let authedClient = client.getAuthenticated(token: self.token!)
        //Create an authenticated client instance
        
        let result = try await authedClient.getHomeTimeline()
        //Load some content
    }

此外,确保为您的自定义 URL 设置一个处理程序

    ContentView()
        .onOpenURL { url in
            MastodonClient.handleOAuthResponse(url: url)
        }

要求

作者

许可证

MastodonClient 在 MIT 许可证下可用。有关更多信息,请参阅 LICENSE 文件。