使用Swift编写的Web服务有问题。
启动Web服务运行完美,方法connectionDidFinishLoading
(WebServiceHelper)获取正确的数据。
现在我想调用一个单独的函数(在本例中是在LoginViewController中,稍后在其他控制器中),具体取决于启动Web服务的函数。
在JavaScript中我会使用回调,但在Swift文档中找不到这样的内容。
class WebServiceHelper: NSObject, NSURLConnectionDelegate, NSXMLParserDelegate {
var mutableData:NSMutableData = NSMutableData()
var sourceClass:String = ""
var lastUsedService:String = ""
func startWebServiceActivity(xmlMessage:String, method:String, service:String) {
let text: String = xmlMessage
let wsUrl: String = "https://.../webservice/soap/server.php"
let soapMessage:String = text
let url = NSURL(string: wsUrl)
let theRequest = NSMutableURLRequest(URL: url!)
let msgLength = String(soapMessage.characters.count)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
connection?.start()
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
mutableData.length = 0;
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
mutableData.appendData(data)
}
// Parse the result right after loading
func connectionDidFinishLoading(connection: NSURLConnection!) {
//print(mutableData)
let datastring = String(data: mutableData, encoding: NSUTF8StringEncoding)
//print(datastring)
let result = XMLParser.sharedParser.decode(datastring!)
print(result)
}
}
class LoginViewController: UIViewController {
//MARK: IBOutlets
@IBOutlet weak var usernameTextfield: UITextField!
@IBOutlet weak var passwordTextfield: UITextField!
@IBOutlet weak var autoLoginSwitch: UISwitch!
//MARK: Properties
var soapMethod:String = "login"
var username:String = ""
var password:String = ""
let soapMessages:SOAPMessages = SOAPMessages()
//MARK: Functions
override func viewDidLoad() {
super.viewDidLoad()
let backButton = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: navigationController, action: nil)
navigationItem.leftBarButtonItem = backButton
}
//MARK: IBActions
@IBAction func confirmButton(sender: UIButton) {
username = usernameTextfield.text!
password = passwordTextfield.text!
let loginXML:String = soapMessages.getLoginXML(username, password: password)
WebServiceHelper().startWebServiceActivity(loginXML,method: soapMethod, service:"login")
}
}
感谢您的帮助
答案 0 :(得分:1)
代表是另一种方式,但是闭包也是首选