gpt4 book ai didi

ios - 如何从共享类获取 JSON 响应数据到 ViewController?

转载 作者:可可西里 更新时间:2023-11-01 01:08:29 26 4
gpt4 key购买 nike

我没有使用 Alamofire,所以我想在 SharedClass 中使用 JSON post 方法,我想将我的 api 名称和所有参数发送到该函数。最后我想得到回应。我试过了,但没有用。如果不正确,请纠正我,或者如果有任何其他选项可用,请建议我。

我在 SharedClass 中的代码

func postRequestFunction(apiName:String , parameters:String ) -> [String:Any] {

var localURL = "hostname/public/index.php/v/***?"

localURL = localURL.replacingOccurrences(of: "***", with: apiName)

var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)

var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print(error!)
// print("error=\(String(describing: error))")
print("localizedDescription : \(String(describing: error?.localizedDescription))")
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}

do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
print(returnRes)

} catch let error as NSError {
print(error)
}
}

task.resume()

return returnRes
}

在我的 View Controller 类中,我的代码是。我在这里调用函数

func getProjectDetails() {
let response = SharedClass.sharedInstance.postRequestFunction(apiName: "API Name", parameters: parameters)
print(response)
let res = response["Response"] as! [String:Any]
let status = res["status"] as! String

if status == "SUCCESS" {
//I will handle response here
} else {
let message = res["message"] as! String
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: message)
}
}

最佳答案

这是我的解决方案:

class APIManager {

private init () {}

static let shared = APIManager()

func postRequestFunction(apiName: String , parameters: String, onCompletion: @escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {

var localURL = "hostname/public/index.php/v/***?"

localURL = localURL.replacingOccurrences(of: "***", with: apiName)

var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)

var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in

if let error = error {
onCompletion(false, error, nil)
} else {
guard let data = data else {
onCompletion(false, error, nil)
return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
onCompletion(true, nil, returnRes)

} catch let error as NSError {
onCompletion(false, error, nil)
}
} else {
onCompletion(false, error, nil)
}
}
}
task.resume()
}
}

func getProjectDetails() {

/* Notes:

** onCompletion Block Parameters:

success - This indicates whether the API called successfully or not.
error - This indicates errors from either API calling failed, JSON parsing, or httpStatus is not 200.
result - This indicates the JSON parsed result.

** APIManager:

I have renamed your SharedClass to APIManager for better readibility.

** sharedInstance:

I have renamed sharedInstance to shared for better readibility.

*/

APIManager.shared.postRequestFunction(apiName: "API Name", parameters: "parameters") { (success, error, result) in
if success {
if let res = result?["Response"] as? [String: Any] {
if let status = res["status"] as? String {
if status == "SUCCESS" {
//You can handle response here.
} else {
let message = res["message"] as! String
//Call alert function.
}
}
}
} else {
print(error?.localizedDescription)
}
}
}

关于ios - 如何从共享类获取 JSON 响应数据到 ViewController?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52014544/

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