简体   繁体   中英

How Network Layer working in Swift 5 & Xcode 11

Two days already of learning how to make my own network layer to fetching data from server using API and json decoder

But after two days of many lessons online I can't find what's after creating the network layer in Swift 5,

I'm getting json data in output by print(data) in serviceLayer Class file but can't print the data in SwiftUI List View?

here's the serviceLayer.swift file

import Foundation

class ServiceLayer {
    // 1.
    class func request<T: Decodable>(router: Router, completion: @escaping (Result<[String: [T]], Error>) -> ()) {
        // 2.
        var components = URLComponents()
        components.scheme = router.scheme
        components.host = router.host
        components.path = router.path
        components.queryItems = router.parameters
        // 3.
        guard let url = components.url else { return }
        var urlRequest = URLRequest(url: url)
        urlRequest.httpMethod = router.method
        // 4.
        let session = URLSession(configuration: .default)
        let dataTask = session.dataTask(with: urlRequest) { data, response, error in
            // 5.
            guard error == nil else {
                completion(.failure(error!))
                print(error?.localizedDescription)
                return
            }
            guard response != nil else {
                return
            }
            guard let data = data else {
                return
            }
            // 6.
            let responseObject = try! JSONDecoder().decode([String: [T]].self, from: data)
            // 7.
            DispatchQueue.main.async {
                // 8.
                completion(.success(responseObject))
            }
        }
        dataTask.resume()
    }
}

And here is the model I'm using

 struct CollectionItem: Decodable {
    let title: String
    let id: Int
}

In the swift ui define a property with @State property wrapper, assign the responseObject to this property. SwiftUI automatically reloads when the @State property is set.

If you are willing to use Combine, https://dev.to/kevinmaarek/getting-started-with-swiftui-and-combine-dd8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM