我想在UIImage
中展示collectionView
。
从Json数据获取图像路径。
图像路径是从先前分配的变量中获取的,我试图显示图像,但我无法得到它。
API正在运行。
但我试图输出它来检查变量var photo = [Stores.photos]?
的值但它没有显示在控制台上
此外,如果直接应用imageURL而不是变量,则会显示图像。如何为var photo = [Stores.photos]?
分配值
StorePhotoCollectionView
class StorePhotoViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
var store_id = ""
var store : [Store]?
var photo : [Store.photos]?
@IBOutlet weak var mainImage: UIImageView!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var storePhotoUIView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
//Request API
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)
self.store = [json]
self.photo = json.photos
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)
//UIView Corner redius
let uiViewPath = UIBezierPath(roundedRect: storePhotoUIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
let uiViewMask = CAShapeLayer()
uiViewMask.path = uiViewPath.cgPath
storePhotoUIView.layer.mask = uiViewMask
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return photo?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let imageCell : UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "imageCell", for: indexPath)
let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView
print("asssss")
let imageURL = URL(string: "http://127.0.0.1:8000/photos/" + photo![indexPath.row].path)
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
}
}
}
}
return imageCell
}
}
您忘记刷新集合视图,最初为集合视图创建对象
@IBOutlet weak var yourcollectionView: UICollectionView!
在你的主线程UI更新上,刷新UICollectionView
DispatchQueue.main.async {
self.nameLabel.text = json.name
self.locationLabel.text = json.location
yourcollectionView.reloadData()
}
终于从服务器加载图片,你正在进行主线程调用,它会冻结你的应用程序,为图像显示进程看this example
调用dispatchqueue后,尝试添加.resume()
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data{
let image = UIImage(data: data)
DispatchQueue.main.async {
imageView.image = image
}
}
}.resume()
}
如果我是你而不是手动处理响应等我只会使用开源库https://github.com/onevcat/Kingfisher
用法很简单,您不必自己处理这些操作:
imageView.kf.setImage(with: URL(string: "your_url_here"))