[英]Populate collectionView from JSON image url swift
我想在 collectionView 中使用 JSON 解析加載圖像。 我正在獲取圖像 URL 數組,但圖像未顯示在UIImageView
。 在獲取 JSON 數組並將其顯示在UICollectionView
的UIImageView
后,我使用了此代碼。
if let url = NSURL(string: self.Products[indexPath.row].image) {
if let data = NSData(contentsOfURL: url){
cell.product_image.contentMode = UIViewContentMode.ScaleAspectFit
cell.product_image.image = UIImage(data: data)
}
}
但我無法加載圖像,但顯示文本。 我在cellForItemAtIndexPath
方法中使用了這段代碼..誰能告訴我我做錯了什么?
func jsonParsingFromURL(){
// 1
let reposURL = NSURL(string: "http://api.room2shop.com/api/product/GetProducts?categoryId=24&filter=2&pageNumber=1")
// 2
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
do
{
if let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: .AllowFragments) as? NSDictionary {
// 4
if let reposArray = json["ProductList"] as? [NSDictionary] {
// 5
for item in reposArray {
Products.append(ProductList(json: item))
}
}
}
}
catch {
print("Error with Json: \(error)")
}
}
}
這是我的 JSON 解析代碼
要反映更改,您需要使用
self.collectionView?.reloadData()
編輯
1-請用這個替換這個塊,並告訴我你是否正常獲取網址,對我來說我正常獲取網址
for item in reposArray
{
//ProductList(json: item)
//Products.append(ProductList(json: item))
//print(item)
print("__________")
print(item["Image"]!)
}
2-我得到
傳輸安全已阻止明文 HTTP
解決方案在這里。 傳輸安全阻止了明文 HTTP
用這個
// taking the URL , then request image data, then assigne UIImage(data: responseData)
let imgURL: NSURL = NSURL(string: "www.example.com/image.jpg")!
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data,response,error) -> Void in
if ( error == nil && data != nil ) {
func display_image() {
// imageView.post.image = your UIImage
self.imageViewPost.image = UIImage(data: data!)
}
dispatch_async(dispatch_get_main_queue(), display_image)
}
}
task.resume()
// end of loading img
該圖像是一個未保存在本地image.xassets
的 URL,因此您需要使用下面給出的擴展名解析該 URL。
// 添加擴展名
extension UIImageView {
func loadImage(urlString: String) {
let url = URL(string: urlString)!
URLSession.shared.dataTask(with: url, completionHandler: { (data, respones, error) in
if error != nil {
print(error ?? "")
return
}
DispatchQueue.main.async {
self.image = UIImage(data: data!)
}
}).resume()
}
}
// 在你的 vc(你填充的地方)中調用這個語句
yourImageView.loadImage(urlString:yourUrl)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.