/*-----------------------------------------------------*/
/* RestClient.swift */
/*-----------------------------------------------------*/
protocol RestClientDelegate {
func dataDidLoad(json:String)
}
class RestClient {
var delegate:RestClientDelegate
//Handles all the network codes and exceptions
func makeGetRequest(url){
//send a get request to the server
//on error - handle erros
//on success - pass Json response to HttpUser class
delegate.dataDidLoad(jsonOutput)
}
}
/*-----------------------------------------------------*/
/* HttpUser.swift */
/*-----------------------------------------------------*/
protocol UserDelegate(){
func usersDidLoad(usersArray:[User])//User object array
}
class HttpUser, RestClientDelegate {
var delegate:UserDelegate
func getUsers(){
//Use rest client to make an api call
var client = RestClient()
client.delegate = self
client.makeGetRequest("www.example.com/users")
}
//Once RestClient get the json string output, it will pass to
//this function
func dataDidLoad(json:String){
//parse json - Handles json exceptions
//populate user objects in an array
//pass user array to the ViewController
delegate.usersDidLoad(usersArray:[User])
}
}
/*-----------------------------------------------------*/
/* UserViewController.swift */
/*-----------------------------------------------------*/
class UserViewController:UIViewController, UserDelegate {
override viewDidLoad(){
super.viewDidLoad()
//Ask http user class to retrieve users
var httpUser = HttpUser()
httpUser.delegate = self
httpUser.getUsers()
}
//Callback function to get users array
func usersDidLoad(usersArray:[User]) {
//now you have users object array
//populate a table view
}
}
你能告诉我这种方法是否适合遵循? 有没有更好的方法来实现这一目标?
非常感谢大家!
- 请注意:在这种情况下,我不想使用像Alamofire这样的第三方库。
答案 0 :(得分:1)
总的来说,这是一个很好的方法。您可能需要考虑在用户界面上显示错误(例如:无互联网连接)以获得更好的用户体验。在您的示例中,您正在RestClient
类中处理错误,但是如果出现任何错误,则不会将UserViewController
类置于用户界面上进行处理。