标签:body String title url await REST API Alamofire Post
JSON : Placeholder
JSON : Placeholder (https://jsonplaceholder.typicode.com/) 是一个用于测试的 REST API 网站。
以下使用 RxSwift + 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
在向导的第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())
(await Post.getPosts(n: 2)).forEach { print($0) }
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")
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")
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"
}
{}
标签:body,String,title,url,await,REST,API,Alamofire,Post 来源: https://www.cnblogs.com/zwvista/p/16206131.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。