Swift与多个Web服务进行通信

时间:2017-01-29 08:20:34

标签: swift web-services post

我目前需要使用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服务才能获取信息列表。

目前使用登录按钮调用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()


}

1 个答案:

答案 0 :(得分:3)

您遇到了MVC无法工作的复杂性。在编写应用程序时,如果您没有正确使用MVC,代码的复杂性和不必要的重复可能会失控并且您会失去监督。

例如,要使用的样式是创建一个LoginModel和ItemsModel,因为缺少更好的名称。两者都将发出Web请求,因此请务必创建一个处理通用Web请求的类或实现类似Alamofire的框架(其中包含一些很好的身份验证示例和automatic retrying of requests基于令牌等)

现在在你的ViewController中将你的数据的所有处理单独分配给View-Independant 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中处理登录,并在完全独立的模型中处理您使用从loginModel收到的凭据进行实例化的dataModel。当然,这是一个粗略的例子,使用Alamofire,您可以使用Session Manager来处理身份验证(请参阅&#39;自动重试请求的网址&#39;,向下滚动一点并且有一个身份验证的例子。)不需要使用凭证来实例化您的dataModel,这纯粹是为了演示如何拆分代码来处理这些请求。