我目前需要使用web服务来完成一些任务,即登录和接收信息列表。
成功登录后,web服务将返回'response‘信息:{"LoginID":"1","Password":"","Role":"pol","LoginType":"Indevidual","UserID":"6110895204062016","UserRoleID":"20202020202020","RoleID":"999674512042008","PartyId":"1063081525122008","PartyFunctionId":"123123","BranchCode":"10","RoleCode":"123123","Status":{"isError":false,"ErCode":null,"Error":null}}
它需要被发送到另一个web服务以获得信息列表。
当前使用登录按钮调用webserivce才能登录。
如何使用第一个the服务中的信息调用另一个the服务?
更好的想法的代码:
@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()
}
发布于 2017-01-29 17:24:21
您正在体验不在MVC中工作的复杂性。在编写应用程序时,如果您没有正确地使用MVC,那么代码的复杂性和不必要的重复就会失控,并且您会失去监督。
例如,由于缺少更好的名称,可以使用的样式是创建一个LoginModel和一个ItemsModel。两者都会发出web请求,所以一定要创建一个处理通用web请求的类,或者实现一个像Alamofire这样的框架(它有一些很好的基于令牌的身份验证和automatic retrying of requests的示例)
现在,在您的ViewController中,将所有数据处理工作分离到一个独立于视图的LoginClass中,如下所示:
@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中处理登录,在一个完全独立的模型中处理dataModel,并使用从loginModel收到的凭据实例化它。当然,这是一个粗略的例子,使用Alamofire,你可以使用一个Session Manager
,它将负责身份验证(参见“自动重试请求”的网址,向下滚动一点,这是一个身份验证的例子。)消除了使用凭据实例化dataModel的需要,这纯粹是为了演示如何拆分代码来处理这些请求。
https://stackoverflow.com/questions/41918929
复制相似问题