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

问题描述 投票:2回答:2

我没有使用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
}

在我的视图控制器类中,我的代码是。我在这里呼唤功能

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)
    }
}
ios json swift singleton http-post
2个回答
1
投票

这是我的解决方案:

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)
        }
    }
}

1
投票

您忘记了Service的异步范例,您可以在Closure中返回您的API响应,如下所示

func postRequestFunction(apiName:String , parameters:String, returnRes: @escaping ([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)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
        // check for fundamental networking error
        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 {
            if let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
                returnRes(response)
            }
        } catch let error as NSError {
            print(error)
        }
    }

    task.resume()
}

并使用如下

postRequestFunction(apiName: "yourUrl", parameters: "Param") { (response) in

    print(response)

}
© www.soinside.com 2019 - 2024. All rights reserved.