POP网络(一)
2019-08-29 本文已影响0人
Code_人生
override func viewDidLoad() {
super.viewDidLoad()
let request = LGPersonRequest(name: "kody")
request.send { (person) in
self.updataUI(person: person!)
}
}
func updataUI(person:LGPerson){
imageView.image = UIImage(named: person.iconName)
nickName.text = person.name
ageLabel.text = person.age
hobbyLabel.text = person.hobby
petPhraseLabel.text = person.petPhrase
}
- 不同的接口公用一个
LGRequest
协议 - 不同的接口对应不同的
LGXXXRequest
结构体,LGXXXRequest
实现LGRequest
协议 -
associatedtype Response func parse(data: Data) -> Response?
关联类型,泛型 -
LGXXXRequest
关联具体的模型typealias Response = type
,parse
返回关联的模型type
//LGRequest.swift
import UIKit
enum LGHTTPMethod: String {
case GET
case POST
}
protocol LGRequest {
var host: String { get }
var path: String { get }
var method: LGHTTPMethod { get }
var parameter: [String: Any] { get }
associatedtype Response
func parse(data: Data) -> Response?
}
extension LGRequest {
func send(handler: @escaping (Response?) -> Void) {
let url = URL(string: host.appending(path))!
var request = URLRequest(url: url)
request.httpMethod = method.rawValue
// 在示例中我们不需要 `httpBody`,实践中可能需要将 parameter 转为 data
// request.httpBody = ...
let task = URLSession.shared.dataTask(with: request) {
data, response, error in
if let data = data, let res = self.parse(data: data) {
DispatchQueue.main.async { handler(res) }
} else {
DispatchQueue.main.async { handler(nil) }
}
}
task.resume()
}
}
struct LGPersonRequest: LGRequest {
typealias Response = LGPerson
let name: String
let host = "http://127.0.0.1:5000"
var path: String {
return "/pythonJson/getTeacherInfo/?username=\(name)"
}
let method: LGHTTPMethod = .GET
let parameter: [String: Any] = [:]
func parse(data: Data) -> LGPerson? {
return LGPerson(data: data)
}
}
//struct LGLoginRequest: LGRequest {
// typealias Response = type
//
//}
//struct LGHomeRequest: LGRequest {
//
//}
- 模型
LGPerson
结构体
//LGPerson.swift
import UIKit
struct LGPerson {
let name: String
let iconName: String
let age: String
let hobby: String
let petPhrase: String
init?(data: Data) {
guard let obj = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else {
return nil
}
guard let name = obj["name"] as? String else {
return nil
}
guard let iconName = obj["iconName"] as? String else {
return nil
}
guard let age = obj["age"] as? String else {
return nil
}
guard let hobby = obj["hobby"] as? String else {
return nil
}
guard let petPhrase = obj["petPhrase"] as? String else {
return nil
}
self.name = name
self.iconName = iconName
self.age = age
self.hobby = hobby
self.petPhrase = petPhrase
}
}