使用辅助函数进行POST请求

sen*_*nty 1 post helpers ios swift

我尝试为我的POST请求创建一个帮助程序类,并希望返回响应.但是,由于post请求是异步的,它让我感到有点困惑.

我试过返回NSString然而它不让我既不返回也response没有responseString.它只是让我放return "A".我试图使用,-> NSURLResponse但也无法使其工作.

制作像这样的辅助方法的正确方法是什么?(如果我在得到回复后进行检查,并且根据响应返回true或false,这也没关系)

class func hello(name: String) -> NSString {

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
    request.HTTPMethod = "POST"
    let postString = "Hi, \(name)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    task.resume()
    return "A"
}
Run Code Online (Sandbox Code Playgroud)

Fon*_*nix 5

由于dataTaskWithRequest是异步的,函数将在执行完成块之前命中return语句.你应该做的是为你自己的帮助器方法设置一个完成块,或者将某种委托对象传递给该函数,以便你可以调用它上面的方法让它知道webservice回调的结果是什么.

以下是使用完成块的示例:

class func hello(name: String, completion: (String? -> Void)){

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.thisismylink.com/postName.php")!)
    request.HTTPMethod = "POST"
    let postString = "Hi, \(name)"
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {                                                          // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")

        }

        let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        completion(responseString);
    }
    task.resume()
}
Run Code Online (Sandbox Code Playgroud)

然后使用它

<#YourClass#>.hello("name") { responseString in

    //do something with responseString
}
Run Code Online (Sandbox Code Playgroud)

没有测试代码,但应该是正确的