gpt4 book ai didi

json - Swift 如何重用我的 JSON HTTP 请求 header

转载 作者:行者123 更新时间:2023-11-30 12:18:09 25 4
gpt4 key购买 nike

我正在制作一个从 API 发出大量请求的应用程序。所以我不想一遍又一遍地复制和粘贴代码。我想知道如何以更有效的方式重用我的代码?也许有扩展?这是我知道的代码:

func apiRequest() {
let config = URLSessionConfiguration.default
let username = "****"
let password = "****"
let loginString = String(format: "%@:%@", username, password)
let userPasswordData = loginString.data(using: String.Encoding.utf8)
let base64EncodedCredential = userPasswordData?.base64EncodedString()
let authString = "Basic " + (base64EncodedCredential)!
print(authString)
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)

var running = false
let urlProjects = NSURL(string: "https://start.jamespro.nl/v4/api/json/projects/?limit=10")
let task = session.dataTask(with: urlProjects! as URL) {
( data, response, error) in
if let taskHeader = response as? HTTPURLResponse {
print(taskHeader.statusCode)
}
if error != nil {
print("There is an error!!!")
print(error)
} else {
if let content = data {
do {
let dictionary = try JSONSerialization.jsonObject(with: content) as! [String:Any]
print(dictionary)

if let items = dictionary["items"] as? [[String:Any]] {
for item in items {
if let description = item["Description"] as? String {
self.projectNaam.append(description)
}
if let id = item["Id"] as? String {
self.projectId.append(id)
}
if let companyId = item["CompanyId"] as? String {
self.companyId.append(companyId)
}

}
}
self.apiRequestCompani()
}
catch {
print("Error: Could not get any data")
}
}
}
running = false
}


running = true
task.resume()

while running {
print("waiting...")
sleep(1)
}

}

最佳答案

是的,您可以使用扩展来创建 BaseViewController 并在您想要反复使用代码的地方扩展它。然后,您应该将输入参数上的所有动态数据抽象到该方法。

import UIKit
class BaseViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}

func getApiRequest (Parameters) {
//API Request
}

然后在你的 View Controller 中你只需扩展 BaseViewController

class ViewController: BaseViewController {

override func viewDidLoad() {
super.viewDidLoad()

//Call method in baseviewcontroller
getApiRequest(parameters)

//Call method in self
self.getApiRequest(parameters)
}

override func getApiRequest(Parameters) {

//IF you need to override default configuration
}

关于json - Swift 如何重用我的 JSON HTTP 请求 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45138541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com