我如何使用Swift 3发出HTTP请求?

时间:2016-10-20 20:41:09

标签: ios swift swift3 nsurlsession

我正在学习Swift并尝试发出HTTP请求。我的代码正在运行,但我不知道如何返回请求的结果:

// Application module
var crudApp = angular.module('crudApp',[]);
crudApp.controller("DbController",['$scope','$http', function($scope,$http){

// Function to get employee details from the database
getInfo();
function getInfo(){
// Sending request to EmpDetails.php files
$http.post('databaseFiles/empDetails.php').success(function(data){
// Stored the returned data into scope
$scope.details = data;
});
}

有人可以帮我吗?我正在尝试使用CompletionHanlder,但我找到的所有示例都基于swift 2,这会导致我的代码出错

enter image description here

3 个答案:

答案 0 :(得分:2)

完成处理程序的类型必须是这样的:

@escaping ({argument types...})->{result type}
需要

@escaping,因为稍后在通信完成时执行完成处理程序。

{argument types...}需要是您要传递给处理程序的类型,因此在您的情况下,只需要一个类型String。而且您通常不使用处理程序的结果,因此您需要指定Void(又名())。

因此,您的完成处理程序的类型必须是:

@escaping (String)->Void

因此,您的方法标题变为:

(你知道你需要一个关于参数列表的右括号。)

func makeRequest(request: URLRequest, completion: @escaping (String)->Void)

整个方法都是这样的:

func makeRequest(request: URLRequest, completion: @escaping (String)->Void) {
    let task = URLSession.shared.dataTask(with: request) {data, response, error in
        guard let data = data, error == nil else{
            print("error=\(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 = \(response)")
        }
        print(data as NSData) //<-`as NSData` is useful for debugging
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            print(json)
            //Why don't you use decoded JSON object? (`json` may not be a `String`)
        } catch {
            print("error serializing JSON: \(error)")
        }
        //Not sure what you mean with "i need to return the json as String"
        let responseString = String(data: data, encoding: .utf8) ?? ""
        completion(responseString)
    }
    task.resume()
}

您可以将其用作:

    makeRequest(request: request) {response in //<-`response` is inferred as `String`, with the code above.
        print(response)
    }

答案 1 :(得分:1)

func makeRequest(request: URLRequest, completion: (result : String?)->() {
    let task = URLSession.shared.dataTask(with: request){data, response, error in
    guard let data = data, error == nil else{
        print("error=\(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 = \(response)")
    }
    print (data)
    do {
        let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
            print(json)
        } catch {
            print("error serializing JSON: \(error)")
        }
        completion("yourResultString")
    //print("responseString = \(responseString)")

    }
    task.resume()
}

来称呼它

makeRequest(request: request) { (result : String?) in 
    if let result = result {
        print("got result: \(result)")
}

答案 2 :(得分:0)

您无法“返回”请求的结果。当你得到一个结果时,你的makeRequest函数已经返回给它的调用者。你应该:

  1. makeRequest更改为不返回任何内容,因为没有 点
  2. 将注释掉的print语句替换为代码 结果为responseString的内容。