Simple MVVM in Swift

Model-view-viewmodel (MVVM) is a software architecture for developing user interfaces. you can implementation this architecture in developing android, ios or other programming languages that support OOP. Now we implement this architecture in swift language and collaborate with RXSwift and RXCocoa.

Step instalation :

- pod init 

- open podfile 

- add RXCocoa and RXSwift

- pod install

- open project in xcode 

Simple experience you need you just need :

- Model : are use for handle structure response API  ,  can use

  • data struct
  • data class

- ViewModel : Handle process request response, can user :

  • Alamofire
  • Moya 
  • or default swift URL

 - View : are use for dispaly interface

flow MVVV in swift

Example MVVM with struct and default URL swift :

  • Model Structure

struct Post: Decodable {
    let id: Int
    let title: String
    let body: String
}

  • ViewModel 

    class PostViewModel {
        var posts = BehaviorRelay<[Post]>(value: []) 
        
        func getPosts() {
            showLoading() //show loading when proccess
            self.apidelegate.loading(tagrequest: tagpost, status: true)
            guard let urlpost = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
            URLSession.shared.dataTask(with: urlpost) { (data, response, error) in
                hiddenLoading //hidden loading when process end
                do {
                    self.posts.accept(try JSONDecoder().decode([Post].self, from: data!))
                } catch let error {
                    print("error :", error)
                }
            }.resume()
        }
    }
    • View
    - Controller :
    class PostsViewController: UIViewController {
        @IBOutlet weak var tableviewPosts: UITableView!
        var loginviewmodel = LoginViewModel()
        override func viewDidLoad() {
            super.viewDidLoad() 
            getDataPosts()
        }
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated) 
        }
        func getDataPosts() {
            postviewmodel?.getPosts()
            postviewmodel?.posts.bind(to: tableviewPosts.rx.items(cellIdentifier: "PostsViewCell",
                                                                 cellType: PostViewCell.self)) {
                rowcell, postdata, postcell in
                postcell.labelTitle.text = postdata.title
            }
        }
    }


      - Cell :
      class PostViewCell: UITableViewCell {
          @IBOutlet weak var labelTitle: UILabel!
      }

















        Simple MVVM in Swift Simple MVVM in Swift Reviewed by sdiik on نوفمبر 14, 2020 Rating: 5

        ليست هناك تعليقات:

        يتم التشغيل بواسطة Blogger.