2016-07-20 49 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/