运行此代码时,它在我的collectionView
中什么也没有显示。
我的代码-
class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
var AllImage: [String] = []
var boolValue = false
override func viewDidLoad() {
super.viewDidLoad()
collectionView.delegate = self
collectionView.dataSource = self
downloadJson()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("Found - \(AllImage.count)")
return AllImage.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
cell.myImage.image = UIImage(named: AllImage[indexPath.row])
return cell
}
//MARK: Image
func downloadJson(){
var access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwMjc2LCJpc3MiOiJodHRwczovL2hvbWlpdGVzdC5jby56YS9hcGkvbG9naW4iLCJpYXQiOjE1NTIxOTYwMjIsImV4cCI6MTU1NDc4ODAyMiwibmJmIjoxNTUyMTk2MDIyLCJqdGkiOiJBeTY5R0JkZDA5dWdFTDBhIn0.czpQQsC08vuTB8iGdTeEjjQUmzl6I5Cs0VQ8WeA5VaY"
let headers = ["Authorization": "Bearer "+access_token+"", "Content-Type": "application/json"]
Alamofire.request("https://homiitest.co.za/api/gallery", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
if response.result.isSuccess{
print(response)
let swiftyJson = JSON(response.data!)
let productTemplate = swiftyJson["data"].array
print("hello there - \(productTemplate)")
for product in productTemplate! {
if let data = product["data"].bool {
continue
} else
{
print("I am in this block")
self.AllImage.append(product.stringValue)
}
self.collectionView!.reloadData()
}
}
}
}
}
答案 0 :(得分:1)
UIImage(名称:String)从资产目录中加载图像。由于AllImage包含图像的网址,因此您需要先下载每个图像,然后再显示它。我建议使用一个库(Kingfisher是一个很棒的库,并且相当容易使用)。 您需要替换此行代码
cell.myImage.image = UIImage(named: AllImage[indexPath.row])
使用
let url = URL(string: AllImage[indexPath.row])
cell.myImage.kf.setImage(with: url)
答案 1 :(得分:1)
只需添加此功能
func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:@escaping (UIImage?) -> Void){
if image != nil && imageView != nil {
imageView!.image = image!
}
var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
urlcatch = documentpath + "/" + "\(urlcatch)"
let image = UIImage(contentsOfFile:urlcatch)
if image != nil && imageView != nil
{
imageView!.image = image!
compate(image)
}else{
if let url = URL(string: imgUrl){
DispatchQueue.global(qos: .background).async {
() -> Void in
let imgdata = NSData(contentsOf: url)
DispatchQueue.main.async {
() -> Void in
imgdata?.write(toFile: urlcatch, atomically: true)
let image = UIImage(contentsOfFile:urlcatch)
compate(image)
if image != nil {
if imageView != nil {
imageView!.image = image!
}
}
}
}
}
}
}
只需替换
cell.myImage.image = UIImage(named: AllImage[indexPath.row])
使用
// Here imgPicture = your imageView
// UIImage(named: "placeholder") is Display image brfore download and load actual image.
NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: cell.myImage, imgUrl: AllImage[indexPath.row]) { (image) in }
这是您的第一个数组图像。
答案 2 :(得分:1)
请格式化您的下载代码,您没有将URL字符串保存到数组中以正确加载图像。我已经更新了代码。请参阅下面的内容。
//MARK: Image
func downloadJson(){
let access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwMjc2LCJpc3MiOiJodHRwczovL2hvbWlpdGVzdC5jby56YS9hcGkvbG9naW4iLCJpYXQiOjE1NTIxOTYwMjIsImV4cCI6MTU1NDc4ODAyMiwibmJmIjoxNTUyMTk2MDIyLCJqdGkiOiJBeTY5R0JkZDA5dWdFTDBhIn0.czpQQsC08vuTB8iGdTeEjjQUmzl6I5Cs0VQ8WeA5VaY"
let headers = ["Authorization": "Bearer "+access_token+"", "Content-Type": "application/json"]
Alamofire.request("https://homiitest.co.za/api/gallery", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
if response.result.isSuccess{
//print(response)
let swiftyJson = JSON(response.data!)
let productTemplate = swiftyJson["data"].array
//print("hello there - \(productTemplate)")
for product in productTemplate! {
// print(product["image_medium"].stringValue)
self.AllImage.append(product.stringValue)
print("this is data - \(product.stringValue)")
}
self.collectionView!.reloadData()
}
}
}
答案 3 :(得分:0)
如果您不想安装pod,请尝试此操作。 让imageCache = NSCache()
extension UIImageView {
func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) {
self.image = nil
if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
self.image = cachedImage
return
}
self.image = placeHolder
if let url = URL(string: URLString) {
URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
if error != nil {
print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
return
}
DispatchQueue.main.async {
if let data = data {
if let downloadedImage = UIImage(data: data) {
imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
self.image = downloadedImage
}
}
}
}).resume()
}
}
}
使用:
cell.myImage.imageFromServerURL(AllImage[indexPath.row], placeHolder:PLACEHOLDER_IMAGE)
如果您有任何疑问,请告诉我。
答案 4 :(得分:0)
如果您不想使用AlamofireImage,AFNetworking,SDWebImage等其他库,仍然可以使用Alamofire。
extension UIImageView {
func showImages(imageURL: String) {
Alamofire.request(imageURL, method: .get)
.validate()
.responseData(completionHandler: { (responseData) in
self.image = UIImage(data: responseData.data!)
})
}}
您可以像这样使用它:
cell.myImage.showImages(AllImage[indexPath.row])