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

时间:2018-08-25 06:12:39

标签: ios json swift singleton http-post

我没有使用Alamofire,所以我想在SharedClass中使用JSON发布方法,并且想将我的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)
    }
}

2 个答案:

答案 0 :(得分:1)

您忘记了服务的异步模式,可以像下面这样在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)

}

答案 1 :(得分: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)
        }
    }
}