Как получить данные ответов JSON из общего класса в ViewController? - PullRequest
0 голосов
/ 25 августа 2018

Я не использую Alamofire, поэтому я хочу использовать JSON post подход в SharedClass, и я хочу отправить свое имя 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 голосов
/ 30 августа 2018

Вот мое решение:

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)
        }
    }
}
0 голосов
/ 25 августа 2018

Вы забыли асинхронную парадигму Сервиса. Вы можете вернуть свой ответ API в Closure, как показано ниже

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)

}
...