Swift 与多个Web服务进行快速通信
我目前需要使用web服务来完成一些任务,包括登录和接收信息列表 成功登录后,web服务将返回“响应”信息:Swift 与多个Web服务进行快速通信,swift,web-services,post,Swift,Web Services,Post,我目前需要使用web服务来完成一些任务,包括登录和接收信息列表 成功登录后,web服务将返回“响应”信息:{“LoginID”:“1”、“密码”:“角色”:“pol”、“LoginType”:“独立”、“用户ID”:“6110895204062016”、“用户RoleID”:“202020202020”、“RoleID”:“99974512042008”、“PartyId”:“1063081525122008”、“PartyFunctionId”:“123123”、“BranchCode”:“1
{“LoginID”:“1”、“密码”:“角色”:“pol”、“LoginType”:“独立”、“用户ID”:“6110895204062016”、“用户RoleID”:“202020202020”、“RoleID”:“99974512042008”、“PartyId”:“1063081525122008”、“PartyFunctionId”:“123123”、“BranchCode”:“10”、“RoleCode”:“123123”、“状态”:{“isError”:false,“ErCode”:null,“Error”:null}
需要发送到另一个web服务以获取信息列表
目前正在使用登录按钮调用webserivce以便能够登录
如何使用第一个Web服务中的信息调用另一个Web服务
更好想法的代码:
@IBAction func GetPolicyListButton(_ sender: Any) {
//I will need the information from the second web service to display after clicking this button.. how?
}
@IBAction func LoginButton(_ sender: Any) {
let postString = "cpr=\(usernameField.text!)&password=\(passwordField.text!)"
let url = URL(string:"http://login")!
let postData:Data = postString.data(using: String.Encoding.utf8, allowLossyConversion: false)!
let postLength:String = String(postData.count) as String
var request:URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
let httpStatus = response as? HTTPURLResponse
print("statusCode should be 200, but is \(httpStatus!.statusCode)")
print("response = \(response!)")
print(postString)
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString!)")
let start = responseString!.index(responseString!.startIndex, offsetBy: 75)
let end = responseString!.index(responseString!.endIndex, offsetBy: -9)
let range = start..<end
let jsonStr = responseString!.substring(with: range)
print(jsonStr)
let data1 = jsonStr.data(using: .utf8)!
_ = try? JSONSerialization.jsonObject(with: data1) as? [String: Any]
let persondata = try? JSONSerialization.jsonObject(with: data, options: .allowFragments)
let personInfodata = persondata as? [String : Any]
_ = personInfodata?[""] as? [String : Any]
if (responseString?.contains("1001"))!{
DispatchQueue.main.async {
print("incorrect - try again")
let alert = UIAlertController(title: "Try Again", message: "Username or Password Incorrect", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
else{
DispatchQueue.main.async {
print("correct good")
let storyboard = UIStoryboard(name: "Maintest", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "correctone")
self.present(controller, animated: true, completion: nil)
}
}
}
task.resume()
}
@iAction func GetPolicyListButton(\uSender:Any){
//单击此按钮后,我需要显示第二个web服务中的信息。如何显示?
}
@iAction func登录按钮(\发送方:任意){
让postString=“cpr=\(usernameField.text!)&password=\(passwordField.text!)”
让url=url(字符串:http://login")!
让postData:Data=postString.Data(使用:String.Encoding.utf8,allowLossyConversion:false)!
让postLength:String=String(postData.count)作为字符串
var-request:URLRequest=URLRequest(url:url)
request.httpMethod=“POST”
request.httpBody=postData
setValue(postLength为字符串,forHTTPHeaderField:“内容长度”)
request.setValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=URLSession.shared.dataTask(with:request){data,response,中的错误
保护let数据=数据,错误==nil else{
打印(“错误=\(错误)”)
返回
}
让httpStatus=响应为?HTTPURLResponse
打印(“状态代码应为200,但为\(httpStatus!.statusCode)”)
打印(“响应=\(响应!)”)
打印(postString)
let responseString=String(数据:数据,编码:.utf8)
打印(“responseString=\(responseString!)”)
让start=responseString!.index(responseString!.startIndex,offsetBy:75)
让end=responseString!.index(responseString!.endIndex,offsetBy:-9)
let range=start..您正在经历不在中工作的复杂性。在编写应用程序时,如果您没有正确使用MVC,那么复杂性和不必要的代码复制可能会失控,您将失去监督
例如,要使用的一种样式是,创建一个LoginModel和一个ItemsModel,因为没有更好的名称。这两种样式都会生成web请求,因此请确保创建一个处理一般web请求的类或实现一个框架,如(其中有一些用于身份验证和基于令牌等的优秀示例)
现在,在ViewController中,将所有数据处理分离到视图独立登录类,如下所示:
@IBAction func LoginButton(_ sender: UIButton) {
guard let username = usernameField.text else { "no username" ; return }
guard let password = passwordField.text else { "no password" ; return }
self.loginModel.login(username : username, password: password) {[weak self] succes in
if succes == true {
let dataModel = dataModel(credentials : credentialStyle)
dataModel.loadItems { items : [Item]? in
// Dispatch items to main queue
}
}
}
}
现在,在loginModel中,您处理登录,在一个完全独立的模型中,您处理使用从loginModel收到的凭据实例化的数据模型。当然,这是一个粗略的示例,使用Alamofire,您可以使用会话管理器来处理身份验证(请参阅“自动重试请求”的URL,向下滚动一点,这里有一个身份验证示例。)不再需要使用凭据实例化数据模型,这纯粹是为了演示如何拆分代码以处理这些请求。我的意思是,一般的答案是将代码放入URLSession的完成处理程序中,该处理程序从您的响应中获取数据并调用另一个URLSession。是否有什么东西阻止您这样做?您可以将moya与alamofire一起使用来封装我目前用于处理alamofire内置抽象的所有API调用,moya是否有比alamofire更好/更高效的一些功能?