Web Services 与多个Web服务进行Swift通信

pbwdgjma  于 2022-11-15  发布在  Swift
关注(0)|答案(1)|浏览(132)

我目前需要使用Web服务来完成一些任务,包括登录和接收信息列表。
成功登录后,Web服务将返回“响应”信息:{"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服务以获得信息列表。
当前使用登录按钮调用webservce即可登录。
如何使用第一个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()

}
u0sqgete

u0sqgete1#

您正在体验不使用MVC的复杂性。在编写应用程序时,如果您没有正确使用MVC,复杂性和不必要的代码重复可能会失控,您会失去监督。
例如,可以使用的一种风格是,创建一个LoginModel和一个ItemsModel,因为没有更好的名称。这两个模型都将发出Web请求,所以请确保创建一个处理通用Web请求的类,或者实现一个类似Alamofire的框架(其中有一些很好的示例,用于基于令牌等进行身份验证和自动重试请求)
现在,在ViewController中,将所有数据处理分离到一个与视图无关的LoginClass中,如下所示:

@IBAction func LoginButton(_ sender: UIButton) {
    guard let username = usernameField.text else { print("no username") ; return }
    guard let password = passwordField.text else { print("no password") ; return }

    self.loginModel.login(username: username, password: password) { [weak self] success in 

        if success {
            let dataModel = dataModel(credentials: credentialStyle)

            dataModel.loadItems { items : [Item]? in 
                // Dispatch items to main queue
            }
        }
    }
}

现在在loginModel中处理登录,在一个完全独立的模型中处理dataModel,使用从loginModel接收的凭证示例化dataModel。(请参阅“自动重试请求”的URL,向下滚动一点,就会看到一个身份验证示例。)不需要使用凭据示例化dataModel,这纯粹是为了演示如何拆分代码来处理这些请求。

相关问题