简体   繁体   中英

How can I access the User properties inside my HomeViewController from my NetworkingService response?

How can I access the User properties inside my HomeViewController from my NetworkingService response??

I am able to print all the users in my NetworkingService but I need to access them inside ViewDidLoad in my HomeViewController.

So far this is my code in my NetworkingService which prints the properties:

import Foundation

class NetworkingService {

    static let shared = NetworkingService()

    let session = URLSession.shared

    func getUsers(success successBlock: @escaping (GetUsersResponse) -> Void) {

        guard let url = URL(string: "") else
        { return }

        session.dataTask(with: url) { (data, response, error) in

            if let error = error { print(error); return }
            do {
                let decoder = JSONDecoder()
                let dateFormatter = DateFormatter()
                dateFormatter.locale = Locale(identifier: "en_US_POSIX")
                dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
                decoder.dateDecodingStrategy = .formatted(dateFormatter)
                let result = try decoder.decode(Root.self, from: data!)
                for user in result.users {
                    print(user.id ?? "", user.name ?? "", user.userName ?? "", user.createdDate ?? "", user.profileImage ?? "")

                }
            } catch {
                print(error)
            }

            }.resume()
    }
}

This above code prints all the users from inside the NetworkingService but I need to access them in my ViewController which looks like this:

import UIKit

class HomeViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    let usersArray: [String] = []

    override func viewDidLoad() {
        super.viewDidLoad()
        NetworkingService.shared.getUsers { (response) in

        }
    }

    //Number of views
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return usersArray.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let userCell = collectionView.dequeueReusableCell(withReuseIdentifier: "UserCollectionViewCell", for: indexPath) as! UserCollectionViewCell
        userCell.backgroundColor = UIColor.green
        return userCell
    }
}

I also have this User struct:

import Foundation

struct Root: Decodable {
    let users: [User]
}

    struct User : Decodable {
        let id: Int?
        let name: String?
        let userName: String?
        let profileImage: URL?
        let createdDate: Date?
}

As well as this GetUserResponse struct which is currently doing nothing:

import Foundation

struct GetUsersResponse {

}

How can I get the values printed in my NetworkingService to show up in labels in my HomeViewController ViewDidLoad? Thank you so much!!

You need

 var usersArray = [Users]()

NetworkingService.shared.getUsers { (response) in
  self.usersArray = response 
  DipsatchQueue.main.async {
    self.collectionView.reloadData()
  }
}

And change

func getUsers(success successBlock: @escaping ([Users]) -> Void) {

    guard let url = URL(string: "") else
    { return }

    session.dataTask(with: url) { (data, response, error) in

        if let error = error { print(error); return }
        do {
            let decoder = JSONDecoder()
            let dateFormatter = DateFormatter()
            dateFormatter.locale = Locale(identifier: "en_US_POSIX")
            dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            decoder.dateDecodingStrategy = .formatted(dateFormatter)
            let result = try decoder.decode(Root.self, from: data!)
            for user in result.users {
                print(user.id ?? "", user.name ?? "", user.userName ?? "", user.createdDate ?? "", user.profileImage ?? "")

            }
            success(result.users ?? [] )
        } catch {
            print(error)
        }

        }.resume()
}

Also change cellForItemAt to display every user may be in an attached UILabel outlets inside the collection cell

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