Can Somebody Post a Good Example of MVC Pattern in Swift

Can somebody post a good example of MVC Pattern in Swift?

This is a typical example of Model View Controller in swift:

class Article {
var title: String
var body: String
var date: NSDate
var thumbnail: NSURL
var saved: Bool
}

class ArticleViewController: UIViewController {
var bodyTextView: UITextView
var titleLabel: UILabel
var dateLabel: UILabel

var article: Article {
didSet {
titleLabel.text = article.title
bodyTextView.text = article.body

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
dateLabel.text = dateFormatter.stringFromDate(article.date)
}
}
}

Understanding MVC pattern used in iOS apps

This sample code demonstrates a multi-stage approach to loading and displaying a UITableView. I think it's really interesting to dive in. It will show MVC in the works.

How to implement simple MVC design pattern in Swift?

I am just sharing my answer here and I am using a codable. It will be useful for anyone:

Model:

import Foundation

struct DataModelItem: Codable{
struct Result : Codable {
let icon : String?
let name : String?
let rating : Float?
let userRatingsTotal : Int?
let vicinity : String?

enum CodingKeys: String, CodingKey {
case icon = "icon"
case name = "name"
case rating = "rating"
case userRatingsTotal = "user_ratings_total"
case vicinity = "vicinity"
}
}
let results : [Result]?
}

NetWork Layer :

import UIKit

protocol DataModelDelegate:class {
func didRecieveDataUpdata(data:[String])
func didFailUpdateWithError(error:Error)
}

class DataModel: NSObject {
weak var delegate : DataModelDelegate?
var theatreNameArray = [String]()
var theatreVicinityArray = [String]()
var theatreiconArray = [String]()
func requestData() {
Service.sharedInstance.getClassList { (response, error) in
if error != nil {
self.delegate?.didFailUpdateWithError(error: error!)
} else if let response = response{
self.setDataWithResponse(response: response as [DataModelItem])
}
}
}

private func setDataWithResponse(response:[DataModelItem]){
for i in response[0].results!{
self.theatreNameArray.append(i.name!)
self.theatreVicinityArray.append(i.vicinity!)
self.theatreiconArray.append(i.icon!)

}
delegate?.didRecieveDataUpdata(data: theatreNameArray)
print("TheatreName------------------------->\(self.theatreNameArray)")
print("TheatreVicinity------------------------->\(self.theatreVicinityArray)")
print("Theatreicon------------------------->\(self.theatreiconArray)")

}
}

Controller :

class ViewController: UIViewController {
private let dataSource = DataModel()
override func viewDidLoad() {
super.viewDidLoad()
dataSource.delegate = self
}

override func viewWillAppear(_ animated: Bool) {
dataSource.requestData()
}

}
extension ViewController : DataModelDelegate{
func didRecieveDataUpdata(data: [DataModelItem]) {
print(data)
}

func didFailUpdateWithError(error: Error) {
print("error: \(error.localizedDescription)")
}

}

APIManager :

class Service : NSObject{
static let sharedInstance = Service()
func getClassList(completion: (([DataModelItem]?, NSError?) -> Void)?) {
guard let gitUrl = URL(string: "") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response
, error) in
guard let data = data else { return }
do {
let decoder = JSONDecoder()
let gitData = try decoder.decode(DataModelItem.self, from: data)
completion!([gitData],nil)

} catch let err {
print("Err", err)
completion!(nil,err as NSError)
}
}.resume()
}
}

MVC design pattern with multiple classes in iOS

In all honesty, it is up to the developer to choose how they structure their data. The MVC, or Model View Controller model is still alive and well but I choose not to use it. Without a who lot of information on what exactly would go into GameLogic.swift, I would say go ahead and try it. Maybe another developer with more experience than me can give you another idea!

MVC design pattern. How does View fit it?

A view's job is to display data and to report events.

The controller's job is to coordinate communication between views and models.

The data's job is store data and also to provide business logic around that data.

You asked:

I'm having trouble understanding were the "Views" fit in.

In your example, the UIPickerView is the view.

In iOS/OSX, a view controller is just the controller of MVC. It just so happens that a view controller also contains an empty view container that you can add all of the other views to. But there is still a clear separation of MVC in iOS/OSX.

All of the classes like UIButton, UIPickerView, UITableView, etc. represent the view. A view controller's job is to provide those views with data from data models as well as respond to events from those views giving you a chance to update other views and the data models.

You also stated:

However every view requires that a View Controller be connected to wire up all the outlets to the view. How am I suppose to keep the View and the View Controller separated?

They are separate. If you add a UITableView, that is a separate view. You connect it to a class so that class can implement the data source and delegate methods. That class is a controller class. It is common for this controller class to be a view controller but it doesn't have to be. You can write all kinds of custom view classes that are independent of any specific view controller (or generic controller). But eventually that view class needs to be hooked up to a [view] controller class so data and events can be processed properly.

You asked:

How or why would I want to have this View Class separated from my View Controller class?

Look at UITableViewController. This is a clear example of the separation but it is provided in a fairly neat package. You actually have a separate UITableView class which is the view. This view is responsible for rendering the view and gathering user interaction. It is the actual table view controller that provides the data to the view and handles the user events from the view.

You can add UITableView views to any view. This is a fully reusable view component. Each controller you hook up to a table view can provide any appropriate data and properly handle user interactions.



Related Topics



Leave a reply



Submit