2016-07-20 43 views
2

朋友!我是Swift的新手。我需要在我的一个视图控制器中创建多个API请求。如果我把所有的代码放在ViewController中,它会很麻烦。 所以我试图开发这个简单的架构来分离概念,但我不确定这是否是处理这种情况的最佳方法。Swift:为网络请求分开的类

/*-----------------------------------------------------*/ 
/* 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 
    } 

} 
  1. RestClient.swift - 使API请求,并传递一个JSON输出。该类包含与网络GET/POST请求有关的所有代码。我可以在将来修改此类而不影响其他类。
  2. HttpUser.swift - 获取json输出创建一个Users数组并传递它。这个类不关心网络请求。它只会处理JSON响应并将其解析为对象数组。我将拥有多个这些。 (例如:HttpBlogs,HttpComments)
  3. UserViewController.swift - 获取用户数组并填充表视图。这将仅处理与UI相关的部分。

你能告诉我这种方法很好吗? 有没有更好的方法来实现这一目标?

非常感谢大家!

- 请注意:在这种情况下,我不想使用Alamofire等第三方库。

+1

我对iOS开发相当陌生,但对我的观点来说,你的方法非常好。事实上,在开发我的第一个项目时,我提出了相同的方法,并且从那时起就非常满意地使用它。一些建议 - 将你的委托变量声明为弱变量。 – Elena

+0

谢谢!我今天在我的应用程序中试过这个代码。它看起来很干净。 :P –

回答

1

一般来说,这是一个很好的方法。您可能想要考虑在用户界面上显示错误(例如:无法连接互联网),以获得更好的用户体验。在你的例子中,你正在处理RestClient类中的错误,但是如果出现任何错误,它不会在UserViewController类中被用于在用户界面上处理。

我发现这篇文章解释了如何编写你自己的网络库的细节。 http://ilya.puchka.me/networking-in-swift/