zwvista

导航

使用 Swift 并发 + Alamofire 调用 REST API

JSON : Placeholder

JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 Swift 并发 + Alamofire 调用该网站的 REST API,获取字符串以及 JSON 数据。

  • GET /posts/1
  • GET /posts
  • POST /posts
  • PUT /posts/1
  • DELETE /posts/1

所有 GET API 都返回JSON数据,格式(JSON-Schema)如下:

{
  "type":"object",
  "properties": {
    "userId": {"type" : "integer"},
    "id": {"type" : "integer"},
    "title": {"type" : "string"},
    "body": {"type" : "string"}
  }
}

创建工程

打开 Xcode,File / New / Project..
在 New Project 向导的第1页,选 iOS / App
在向导的第2页的填上 Product Name: SwiftUIExample,interface 选 SwiftUI
在向导的第3页选择任意文件夹点击 Create 按钮创建工程

添加 Alamofire 包

选中工程,在右键菜单中选 Add Packages... 打开 Apple Swift Packages 对话框
在搜索栏中输入 https://github.com/Alamofire/Alamofire
回车开始搜索
选中搜索结果中的 Alamofire,点击 Add Package 按钮关闭对话框。
工程下方会出现 Package Dependencies,其中包含 Alamofire 5.6.1

RestApi

在 SwiftUIExample 工程中添加 RestApi.swift 文件,内容如下:

import Foundation
import Alamofire

class RestApi {
    static func getObject<T: Decodable>(url: String) async -> T {
        try! await AF.request(url).serializingDecodable(T.self).value
    }
    static func getArray<T: Decodable>(url: String) async -> [T] {
        try! await AF.request(url).serializingDecodable([T].self).value
    }
    static func update<T: Encodable>(url: String, body: T) async -> String {
        try! await AF.request(url, method: .put, parameters: body).serializingString().value
    }
    static func create<T: Encodable>(url: String, body: T) async -> String {
        try! await AF.request(url, method: .post, parameters: body).serializingString().value
    }
    static func delete(url: String) async -> String {
        try! await AF.request(url, method: .delete).serializingString().value
    }
    static func getString(url: String) async -> String {
        try! await AF.request(url).serializingString().value
    }
}

Post

在 SwiftUIExample 工程中添加 Post.swift 文件,内容如下:

import Foundation

struct Post : Codable {
    let userId: Int
    let id: Int
    let title: String
    let body: String
    var description: String {
        return "Post {userId = \(userId), id = \(id), title = \"\(title)\", body = \"\(body.replacingOccurrences(of: "\n", with: "\\n"))\"}";
    }
    
    static let url = "https://jsonplaceholder.typicode.com/"

    static func getPostAsString() async -> String {
        await RestApi.getString(url: "\(url)posts/1")
    }
    static func getPostAsJson() async -> Post {
        await RestApi.getObject(url: "\(url)posts/1")
    }
    static func getPosts(n: Int) async -> [Post] {
        let posts: [Post] = await RestApi.getArray(url: "\(url)posts")
        return Array(posts[0..<n])
    }
    static func createPost() async -> String {
        let post = Post(userId: 101, id: 0, title: "test title", body: "test body")
        return await RestApi.create(url: "\(url)posts", body: post)
    }
    static func updatePost() async -> String {
        let post = Post(userId: 101, id: 1, title: "test title", body: "test body")
        return await RestApi.update(url: "\(url)posts/1", body: post)
    }
    static func deletePost() async -> String {
        return await RestApi.delete(url: "\(url)posts/1")
    }
}
  • getPostAsString 方法取出第1个Post,返回字符串
  • getPostAsJson 方法取出第1个Post,返回Post对象
  • getPosts 方法取出前n个Post,返回n个Post对象
  • createPost 方法创建1个Post,返回字符串
  • updatePost 方法更新第1个Post,返回字符串
  • deletePost 方法删除第1个Post,返回字符串

SwiftUIExampleApp

在 SwiftUIExampleApp.swift 中添加 SwiftUIExampleApp 类的 init 方法及以下代码。

    init() {
        Task {
            print(await Post.getPostAsString())
            print(await Post.getPostAsJson())
            print(await Post.getPosts(n: 2))
            print(await Post.createPost())
            print(await Post.updatePost())
            print(await Post.deletePost())
        }
    }

输出结果

{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
Post(userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto")
[SwiftUIExample.Post(userId: 1, id: 1, title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", body: "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"), SwiftUIExample.Post(userId: 1, id: 2, title: "qui est esse", body: "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla")]
{
  "body": "test body",
  "id": 101,
  "title": "test title",
  "userId": "101"
}
{
  "body": "test body",
  "id": 1,
  "title": "test title",
  "userId": "101"
}
{}

posted on 2022-04-29 11:54  zwvista  阅读(396)  评论(0编辑  收藏  举报