对 json 数据和显示 collection 视图的不同访问 swift 5

different access to json data and showing to collection view swift 5

你好程序员和工程师,基本上我想访问 json 文件中的每个标题项并将其显示到 collection 视图(有一个包含图像视图和标签的单元格)。我的意思是每个标题和图片都应该安排在 collectionView 中,感谢关注,这是我的 json 数据:

{"end":1,"data":[{"userId":{"Id":"608e3f16adb3d241e83b7e91","name":"maryam","userName":"maryam","email":"mmmaryam@gmail.com","phone":"0921984512"},"isoGld":false,"image":["images/product/2021-05-02T09-40-55.719Z-images.jpg"],"check":false,"date":"2021-05-02T05:49:42.854Z","_id":"608e73a7adb3d241e83b7e97","title":"ytrfds","about":"\n                                        music moein","country":"60895361d3dc582b43f1c4d9","city":"60895370d3dc582b43f1c4da","telePhone":"562866567897654897","countryText":"gtfrd","cityText":"lklk","category":"6067fe1df420e0042cb93209","address":"\n                                        arabic","dateOfEx":"2021-05-09T00:00:00.000Z","dateOfStart":"2021-05-26T00:00:00.000Z","offer":"20","createdAt":"2021-05-02T09:40:55.744Z","updatedAt":"2021-05-02T09:40:55.744Z","__v":0},{"userId":{"Id":"608e3f16adb3d241e83b7e91","name":"maryam","userName":"maryam","email":"mmmaryam@gmail.com","phone":"0921984512"},"isoGld":false,"image":["images/product/2021-05-02T09-47-17.699Z-download (2).jpg"],"check":false,"date":"2021-05-02T05:49:42.854Z","_id":"608e7525adb3d241e83b7e99","title":"abbass fgaderi","about":"\n                                        abass ghaderee","country":"60895361d3dc582b43f1c4d9","city":"60895370d3dc582b43f1c4da","telePhone":"444444444444444","countryText":"gtfrd","cityText":"gfdsxz","category":"6067fe1df420e0042cb93209","address":"\n                                        karaj","dateOfEx":"2021-05-12T00:00:00.000Z","dateOfStart":"2021-05-30T00:00:00.000Z","offer":"25","createdAt":"2021-05-02T09:47:17.740Z","updatedAt":"2021-05-02T09:47:17.740Z","__v":0}]}

还有我的代码:

 lass HomeViewController: UIViewController, UICollectionViewDataSource {


@IBOutlet weak var collectionView: UICollectionView!
let collectionOffer = OfferCollectionViewCell()



var txt : String = "  "
var cid : String = "  "
var numberOfItem : Int = 0
var titleArray : [String] = []
var imageArray : [String] = []
var offerImage : [UIImage] = []


override func viewDidLoad() {
    super.viewDidLoad()
    print("\n iiiiiiiiiid is \(cid)")
    //HomeViewController.shared.fetchOffer()
     fetchOffer()
     collectionView.dataSource = self
    // print("aksha hast : \(imageArray)")
     
   
}
struct welcomeJson: Codable {  // this is where i have this error
let userId : UserID
let isoGld , check : Bool
let image : [String]
let v : Int
let date, id , title,countryid,about , cityid, telePhone, countryText,cityText, category, address, dateOfExpire , dateOfStart , offer , createdAt, updatedAt : String
enum CodingKeys : String , CodingKey {
    case userId
    case isoGld
    case image
    case check
    case date
    case id = "_id"
    case title
    case countryid = "country"
    case cityid = "city"
    case telePhone
    case countryText
    case cityText
    case category
    case address
    case dateOfExpire = "dateOfEx"
    case dateOfStart
    case offer
    case about
    case createdAt
    case updatedAt
    case v = "__v"
}
}
struct UserID : Codable {
       let ID, name, userName , email, phone  : String
       enum CodingKeys : String , CodingKey {
           case ID = "Id"
           case name
           case userName
           case email
           case phone
       }
   }
   struct Data1: Codable {
    var data: [welcomeJson]
    enum Codingkeys :  CodingKey {
        case data
    }
        
   }
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    return numberOfItem
 }
 
 func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cellol = collectionView.dequeueReusableCell(withReuseIdentifier: "OfferCollectionViewCell", for: indexPath) as! OfferCollectionViewCell
   // cellol.offerImageView.image = UIImage(imageLiteralResourceName: imageArray[0])
    cellol.offerImageView.image = UIImage(named: imageArray[0])
    cellol.titleLabel.text = titleArray[0]
    return cellol
    
 }
func fetchOffer()  {
    
    if let url = URL(string: "http://5.63.13.16:8080/api/product/search/getByquerys?page=1&limit=10&city=\(cid)") {
        print("url is : \(url)")
        URLSession.shared.dataTask(with: url) {data,response,error in
            if let data = data {
                let jsondec = JSONDecoder()
                do {
                    let parsedJS = try jsondec.decode(Data1.self, from: data)
                    for element in parsedJS.data {
                       
                        
                        self.numberOfItem = element.title.count
                       
                        self.titleArray.append(element.title)
                       // self.imageArray.append(UIImage(element.image))
                        print("akse ma midoni ine : \(element.image)")
                       self.imageArray.append(element.image[0])
                        print("kole aksa ine : \(self.imageArray)")
                        
                //self.imageArray.append(contentsOf: element.image[0...])
                       // print("deghat kon : \(self.imageArray)")
                        
                    }
                }
                
                catch {
                    print("error is : \(error) ")
                }
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                    
                }
            }
        }.resume()
}

这也是我在模拟器上用这段代码得到的结果:

你的方法行不通。

您将字符串的长度分配给 numberOfItems,这与预期的数字无关。

  • 始终return数据源数组中的项目数在numberOfItems
  • 中动态
  • 切勿将结构拆分为数据源的多个数组。

使用一个数据源数组所以替换

var numberOfItem : Int = 0
var titleArray : [String] = []
var imageArray : [String] = []
var offerImage : [UIImage] = []

var userData = [welcomeJson]() // please name structs with starting uppercase letter

fetchOffer()中替换

let jsondec = JSONDecoder()
do {
    let parsedJS = try jsondec.decode(Data1.self, from: data)
    for element in parsedJS.data {
       
        
        self.numberOfItem = element.title.count
       
        self.titleArray.append(element.title)
       // self.imageArray.append(UIImage(element.image))
        print("akse ma midoni ine : \(element.image)")
       self.imageArray.append(element.image[0])
        print("kole aksa ine : \(self.imageArray)")
        
//self.imageArray.append(contentsOf: element.image[0...])
       // print("deghat kon : \(self.imageArray)")
        
    }
}

let jsondec = JSONDecoder()
do {
    let parsedJS = try jsondec.decode(Data1.self, from: data)
    self.userData = parsedJS.data
}

替换numberOfItems
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return userData.count
}

并将cellForItem替换为

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cellol = collectionView.dequeueReusableCell(withReuseIdentifier: "OfferCollectionViewCell", for: indexPath) as! OfferCollectionViewCell

    let item = userData[indexPath.item]
    if let image = item.image.first {
       print(item.title, image)
       // cellol.offerImageView.image = UIImage(
    }
    cellol.titleLabel.text = item.title
    return cellol
    
}

重要提示:

image的值是一个表示部分URL的字符串。它无法转换为 UIImage。您必须单独下载图像。