Swift 4:如何在CollectionV iew

时间:2018-08-24 03:52:55

标签: ios json swift api

我想基于在collectionViewController的ImageView中API获取的路径显示所有图像。

我正在使用Codable格式化API获取的Json数据。 我想获取其中的所有嵌套数据(for语句的图像)

现在我正尝试通过声明let imagePath = store! [IndexPath.row] .photos.map {$ 0.path}来检索值,但这将是错误Can not convert value of type' Never 'to expected argument type 'String'

StoreViewController

import UIKit
class StoreViewController: 
UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
var store_id = ""
var store : [Store]?

@IBOutlet weak var collectionView: UICollectionView!
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var tagLabel: UILabel!
@IBOutlet weak var UIView: UIView!


override func viewDidLoad() {
    super.viewDidLoad()

    collectionView.dataSource = self
    collectionView.delegate = self



    let url = URL(string: "http://localhost:8000/store/api?store_id=" + store_id)
    let request = URLRequest(url: url!)
    let session = URLSession.shared

    let encoder: JSONEncoder = JSONEncoder()
    encoder.dateEncodingStrategy = .iso8601
    encoder.outputFormatting = .prettyPrinted

    session.dataTask(with: request){(data, response, error)in if error == nil,
        let data = data,
        let response = response as? HTTPURLResponse{

        let decoder: JSONDecoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        do {

            let json = try decoder.decode(Store.self, from: data)

            //                for store in (json.stores){
            //                    for photo in (store.photos){
            //                        print(photo.path as Any)
            //                    }
            //                }


            self.store = [json]

            DispatchQueue.main.async {
                self.nameLabel.text = json.name
                self.locationLabel.text = json.location
            }

        } catch {
            print("error:", error.localizedDescription)

        }

        }

        }.resume()

}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    let uiViewPath = UIBezierPath(roundedRect: UIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
    let uiViewMask = CAShapeLayer()
    uiViewMask.path = uiViewPath.cgPath
    UIView.layer.mask = uiViewMask

    //tags
    tagLabel.textAlignment = NSTextAlignment.center
    let tagLabelPath = UIBezierPath(roundedRect: tagLabel.bounds, byRoundingCorners: [.topLeft, .topRight,.bottomLeft,.bottomRight], cornerRadii: CGSize(width: 8, height: 8))
    let tagLabelmask = CAShapeLayer()
    tagLabelmask.path = tagLabelPath.cgPath
    tagLabel.layer.mask = tagLabelmask

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

//Collection
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let imageCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)

    let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView
    //let imageView = UIImageView(frame: CGRect(x:0, y:0, width:imageCell.frame.size.width, height:imageCell.frame.size.height))

    let imagePath = store![indexPath.row].photos.map{$0.path}
    let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + imagePath)
    if imageURL == nil {
        print("nil")
    }else{
        DispatchQueue.global().async {
            let data = try? Data(contentsOf: imageURL!)
            if let data = data {
                let image = UIImage(data: data)
                DispatchQueue.main.async {
                    imageView.image = image
                }
            }
        }
    }

    //print(store)
    print(imagePath)
    return imageCell
}

func collectionView(_ collectionView: UICollectionView,
                    numberOfItemsInSection section: Int) -> Int {

   return store?.count ?? 0
}


}

可编码

struct Store : Codable {
let id : Int
let name : String
let location : String
let price : String
let open_time : String
let closed_day : String
let categories : [categories]
let tags : [tags]
let photos : [photos]

struct categories : Codable {
    let id : Int
    let name : String
}

struct  tags: Codable {
    let id : Int
    let name : String
}

struct photos : Codable{
    let id : Int
    let path : String
}
}

我的显示图片 enter image description here

0 个答案:

没有答案