原谅我对swift相当新鲜。我想创建一个习惯于" POST"请求并从服务器获得响应。然后将从服务器返回的参数传递给func,并允许我的主类相应地响应。以下是我的代表和我的主要课程。它没有打印出LoginViewController类中的响应日志。我有点失落,不知道哪里出了问题。关于如何让这个工作或更好的方式来做这个的建议/指示非常感谢。谢谢!
委派课程
import Alamofire
protocol ServletDelegate {
func responseSuccess(sender: Servlet, respArray : [String])
func responseFail(sender: Servlet, respArray : [String])
}
class Servlet : UIViewController{
var delegate:ServletDelegate?
//form 'data' parameter
Alamofire.request(.POST, Config.flURL, parameters:["data" : ""]).responseData {
response in
print ("request \(response.request)")
print ("response \(response.response)")
print ("result \(response.result)")
print ("data \(response.data)")
let responseData = NSString (data: response.data!, encoding: NSUTF8StringEncoding)
result = (responseData?.componentsSeparatedByString("~z0@"))!
print("responseData :\(responseData)");
print("result :\(result)");
self.delegate?.responseSuccess(self, respArray: result);
}
主要类
class LoginViewController: Servlet, UITextFieldDelegate, ServletDelegate {
@IBAction func submitBtnAction(sender: UIButton) {
Servlet().LoginUserHttp(tfUsername.text!, userPassword: tfPassword.text!);
}
func responseSuccess(sender: Servlet, respArray: [String]) {
print("responseSuccess: \(respArray)");
}
func responseFail(sender: Servlet, respArray: [String]) {
print("responseFail: \(respArray)");
}
}
答案 0 :(得分:3)
首先,你的servlet类不应该是UIViewController,第二个 - 不要使用;很快,它是多余的,第三个你没有设置代表,第四个是代表应该是弱的,这样你就不会遇到强大的参考周期,第五个我没有看到通过发送者的理由
顺便说一句,你可能应该通过响应失败的委托传递一些错误对象,但这取决于你
委派课程
import Alamofire
protocol ServletDelegate: class {
func responseSuccess(respArray : [String])
func responseFail(respArray : [String])
}
class Servlet {
weak var delegate:ServletDelegate?
//form 'data' parameter
Alamofire.request(.POST, Config.flURL, parameters:["data" : ""]).responseData {
response in
print ("request \(response.request)")
print ("response \(response.response)")
print ("result \(response.result)")
print ("data \(response.data)")
let responseData = NSString (data: response.data!, encoding: NSUTF8StringEncoding)
result = (responseData?.componentsSeparatedByString("~z0@"))!
print("responseData :\(responseData)")
print("result :\(result)")
self.delegate?.responseSuccess(respArray: result)
}
主要类
class LoginViewController: UIViewController, UITextFieldDelegate, ServletDelegate {
let servlet = Servlet()
@IBAction func submitBtnAction(sender: UIButton) {
/// im guessing you know what you are doing here, because we dont see that LoginUserHttp in your Servlet code
servlet.LoginUserHttp(tfUsername.text!, userPassword: tfPassword.text!)
}
override func viewDidLoad() {
servlet.delegate = self
}
func responseSuccess(respArray: [String]) {
print("responseSuccess: \(respArray)")
}
func responseFail(respArray: [String]) {
print("responseFail: \(respArray)")
}
}