我尝试使用Swift for Ios Project创建MVVM模式。我研究了来自Internet的各种资源。最后,我为MVVM创建了以下内容。一切正常。但是我不知道这是不是MVVM代码。请向任何人解释。
这是将数据从API解析为标签的示例。 https://the-flash@bitbucket.org/the-flash/samplemvvm.git
查看
<div class="shadow">
<img src="https://picsum.photos/300/300?image=1015">
</div>
查看模型
APICall.swift
//
// ViewController.swift
// SampleMVVM
//
// Created by ADMIN on 20/02/19.
// Copyright © 2019 ADMIN. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var NameLabel: UILabel!
@IBOutlet var ClassLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
service().forStudentName { cName, cClass in
let custViewModel = ViewModel(data: Model(myName: cName[0], myClass: cClass[0]))
DispatchQueue.main.async {
self.NameLabel.text = custViewModel.CustName
self.ClassLabel.text = custViewModel.CustClass
}
}
}
}
ViewModel.swift
//
// APICall.swift
// SampleMVVM
//
// Created by ADMIN on 20/02/19.
// Copyright © 2019 ADMIN. All rights reserved.
//
import UIKit
import Foundation
struct service{
func forStudentName(completionBlock: @escaping (Array<String>, Array<String>) -> Void) {
var CstmrName = Array<String>()
var CstmrClass = Array<String>()
let task = URLSession.shared.dataTask(with: URL(string: DefaultData.Base().Url)!){ data, response, error in
guard let jsonData = data else { return }
do {
let studentData = try JSONDecoder().decode(StudentData.self, from: jsonData)
for index in studentData.studentdetails{
CstmrName.append(index.studentname)
CstmrClass.append(index.studentdetailClass)
}
completionBlock(CstmrName, CstmrClass)
}catch let error {
print(error)
}
}
task.resume()
}
}
模型
Model.swift
//
// ViewModel.swift
// SampleMVVM
//
// Created by ADMIN on 20/02/19.
// Copyright © 2019 ADMIN. All rights reserved.
//
import UIKit
class ViewModel: NSObject {
var CustName: String?
var CustClass: String?
init(data: Model) {
self.CustName = data.CustomerName
self.CustClass = data.CustomerClass
}
}
DefaultData.swift
//
// Model.swift
// SampleMVVM
//
// Created by ADMIN on 20/02/19.
// Copyright © 2019 ADMIN. All rights reserved.
//
import UIKit
//https://next.json-generator.com/api/json/get/4kobjnVE8
/****************************** Student Name Model *********************************/
class Model: NSObject {
var CustomerName: String?
var CustomerClass: String?
init(myName: String, myClass: String) {
CustomerName = myName
CustomerClass = myClass
}
}
/****************************** JSON Parsing Model *********************************/
struct StudentData: Codable {
let studentdetails: [Studentdetail]
}
struct Studentdetail: Codable {
let school, studentname, studentdetailClass, board: String
enum CodingKeys: String, CodingKey {
case school, studentname
case studentdetailClass = "class"
case board
}
}
高级谢谢您的宝贵回答!