заполнить imageview, который внутри представления коллекции - PullRequest
0 голосов
/ 18 декабря 2018

Я получаю ответ и хочу получить только URL-адрес изображения из целых данных и сначала заполнить его в виде коллекции. Позвольте мне показать вам мой код

КОД

func callSubChapAPI(){
    let preferences = UserDefaults.standard
    let studentlvl = "student_lvl"
    let student_lvl = preferences.object(forKey: studentlvl) as! String
    print(student_lvl)
    let params = ["level_id": student_lvl]
    Alamofire.request(subListWithChapter, method: .post, parameters: params).responseData() { (response) in
        switch response.result {
        case .success(let data):
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let subjects = try decoder.decode(SubjectResponse.self, from: data)


        let urls = subjects.subjectList.map({ $0.subList.map({ $0.chImage}) }).reduce([], +)
                print(urls)
                print(subjects)
            } catch {
                print(error.localizedDescription)
            }
        case .failure(let error):
            print(error.localizedDescription)
        }
    }
}

вот моя структура

struct SubjectResponse: Decodable {
    let subjectList: [Subject]
}

struct Subject: Decodable {
    let subList: [Chapter]
}

struct Chapter: Decodable {
    let chId : String
    let chImage: String
    let chName: String
    let conId: String
    let levelId: String
    let subId: String
}

, так что теперь я хочу URL-адрес chImage и задаю для collectionview

Вот ответ

{
    "subject_list" =     (
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 4;
            "sub_list" =             (
                                {
                    "ch_id" = 17;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1530600693.jpg";
                    "ch_name" = " 01. Measurement";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 23;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1451930609.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 24;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1884777188.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                },
                                {
                    "ch_id" = 25;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1518702048.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 4;
                }
            );
            "sub_name" = Physics;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 8;
            "sub_list" =             (
                                {
                    "ch_id" = 26;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1437196139.jpg";
                    "ch_name" = " 1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 8;
                },
                                {
                    "ch_id" = 27;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1903171865.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 8;
                }
            );
            "sub_name" = Chemistry;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 9;
            "sub_list" =             (
                                {
                    "ch_id" = 31;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1319333294.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 9;
                }
            );
            "sub_name" = Testing;
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 10;
            "sub_list" =             (
                                {
                    "ch_id" = 28;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1373218664.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 10;
                }
            );
            "sub_name" = "Test Subject";
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 11;
            "sub_list" =             (
                                {
                    "ch_id" = 29;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/246189282.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 11;
                }
            );
            "sub_name" = "Test Subject 1";
        },
                {
            "con_id" = 2;
            "level_id" = 1;
            "sub_id" = 12;
            "sub_list" =             (
                                {
                    "ch_id" = 30;
                    "ch_image" = "http://mobileapp.xmeducation.com/upload/1342731807.jpg";
                    "ch_name" = "1. Test Chapter";
                    "con_id" = 2;
                    "level_id" = 1;
                    "sub_id" = 12;
                }
            );
            "sub_name" = "Test Subject 2";
        }
    ); 

, поэтому, пожалуйста, скажите мне, чтокак получить URL-адрес ch_image, поэтому я просто хочу знать, что из SubjectResponse, как я могу получить URL-адрес ch_image

Ответы [ 2 ]

0 голосов
/ 18 декабря 2018

Итак, мой ответ:

let subjects: SubjectResponse?

тогда:

self.subjects = try decoder.decode(SubjectResponse.self, from: data)


func numberOfSections(in collectionView: UICollectionView) -> Int {
 return self.subjects.subjectList.count 
}

func collectionView(_ collectionView: UICollectionView, 
 numberOfItemsInSection section: Int) -> Int {
 return self.subjects.subjectList[section].count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt 
    indexPath: IndexPath) -> UICollectionViewCell {
 var url = subject.subjectList[IndexPath.section].sublist[IndexPath.row].chImage
}
0 голосов
/ 18 декабря 2018

Пожалуйста, найдите ниже код.установите numberOfSections count на subjectList count.и для каждого раздела установите значение numberOfItemsInSection на subjectList[section].и в конце получите URL-адрес изображения в методе cellForItemAt и установите его на изображение.

func numberOfSections(in collectionView: UICollectionView) -> Int {
        return subjectList.count
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return subjectList[section].count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // Dequeue your cell here and set the image from 
        // let image_url = subjectList[IndexPath.section][IndexPath.row].ch_image

    }

для получения данных в subjectList.определите subjectList переменную сверху

var subjectList : [Subject]!

в вашем случае успеха Alamofire:

case .success(let data):
            do {
                let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                let subjects = try decoder.decode(SubjectResponse.self, from: data)

self.subjectList = subjects.subjectList
collectionView.reloadData()
...