如何在 JSON 中循环数组 imageURL 以在图像视图中显示
Posted
技术标签:
【中文标题】如何在 JSON 中循环数组 imageURL 以在图像视图中显示【英文标题】:How to loop array imageURL in JSON for show in image view 【发布时间】:2016-09-03 07:43:42 【问题描述】:我有用于循环数据(标题、价格、药物)JSON 的函数,但我无法循环 imageUrl 以在该函数的 imageview 中显示,请帮助查看我的代码。
这个函数barcodeReaded
func barcodeReaded(barcode: String)
print("Barcode is: \(barcode)")
showCodeLabel.text = barcode
let data = NSData(contentsOfURL: episode.thumbnailURL!)
let image = UIImage(data: data!)
self.thumbnailImageView.image = image
let episodes = Episode.downloadAllEpisodes()
var filteredEpisodes = episodes.filter( $0.testCode == barcode )
if filteredEpisodes.count > 0
titleLabel.text = filteredEpisodes[0].title
drugLabel.text = filteredEpisodes[0].drug
priceLabel.text = filteredEpisodes[0].price
//thumbnailImageView.image = filteredEpisodes[0].thumnailURL
这个 JSON 文件
"episode": [
"testCode": "11111111",
"title": "Stomachic mixture 180 ml",
"drug": "AAAAA",
"thumbnailURL": "https://firebasestorage.googleapis.com/v0/b/rxscan-a14ee.appspot.com/o/j01.jpg?alt=media&token=5718797b-fc9c-416e-9394-b544c2880dc9",
"price": "100"
,
"testCode": "22222222",
"title": "Parasetamol 200 ml",
"drug": "BBBBB",
"thumbnailURL": "urlImage",
"price": "150"
,
"testCode": "33333333",
"title": "Beramol 300 ml",
"drug": "CCCCC",
"thumbnailURL": "urlImage",
"price": "120"
]
这段代码
import Foundation
class Episode
var title: String?
var thumbnailURL: NSURL?
var drug: String?
var price: String?
var testCode: String?
init(title: String, thumbnailURL: NSURL, drug: String, price: String, testCode: String)
self.title = title
self.thumbnailURL = thumbnailURL
self.drug = drug
self.price = price
self.testCode = testCode
typealias EpisodeDictionary = [String : AnyObject]
init(espDictionary: EpisodeDictionary)
self.title = espDictionary["title"] as? String
self.thumbnailURL = NSURL(string: espDictionary["thumbnailURL"] as! String)
self.drug = espDictionary["drug"] as? String
self.price = espDictionary["price"] as? String
self.testCode = espDictionary["testCode"] as? String
static func downloadAllEpisodes() -> [Episode]
var episodes = [Episode]()
let jsonFile = NSBundle.mainBundle().pathForResource("testJson3edit6", ofType: "json")
let jsonData = NSData(contentsOfFile: jsonFile!)
if let jsonDictionary = NetworkService.parseJSONFromData(jsonData)
let espDictionaries = jsonDictionary["episodes"] as! [EpisodeDictionary]
for dict in espDictionaries
let episode = Episode(espDictionary: dict)
episodes.append(episode)
return episodes
NetworkService.swift
import Foundation
class NetworkService
// TODO: Make this class be able to download images from a URL
lazy var configuration: NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
lazy var session: NSURLSession = NSURLSession(configuration: self.configuration)
let url: NSURL
init(url: NSURL)
self.url = url
func downloadImage(completion: (NSData -> Void))
let request = NSURLRequest(URL: self.url)
let dataTask = session.dataTaskWithRequest(request) (data, response, error) in
if error == nil
if let httpResponse = response as? NSHTTPURLResponse
switch (httpResponse.statusCode)
case 200:
if let data = data
completion(data)
default:
print(httpResponse.statusCode)
else
print("Error download data: \(error?.localizedDescription)")
dataTask.resume()
extension NetworkService
static func parseJSONFromData(jsonData: NSData?) -> [String : AnyObject]?
if let data = jsonData
do
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers) as? [String : AnyObject]
return jsonDictionary
catch let error as NSError
print("Error processing json data: \(error.localizedDescription)")
return nil
此代码用于获取在 detailViewController 中使用的图像,我不知道如何使用函数barcodeReaded。
if episode.thumbnailURL != nil
if let thumbnailURL = episode.thumbnailURL
let networkService = NetworkService(url: thumbnailURL)
networkService.downloadImage( (data) in
//thumbnailImageView.image = episode.thumbnailURL
let image = UIImage(data: data)
dispatch_async(dispatch_get_main_queue(),
self.thumbnailImageView.image = image
)
)
【问题讨论】:
【参考方案1】:基本上使用thumbnailImageView.image = episode.thumbnailURL
,您正在尝试将String
分配给UIImage
类型的对象。
你应该这样做:
1.从您的 json 字符串中获取 NSURL
let url = NSURL(string: episode.thumbnailURL)!
2。获取NSData
的NSURL
let data = NSData(contentsOfURL: url)!
3.从NSData
分配UIImage
let image = UIImage(data: data)
self.thumbnailImageView.image = image
【讨论】:
对不起,我是初学者当我在函数barcodeReaded中添加代码时,出现错误无法将NSURL转换为第一行代码中的字符串。 @Kopiko inbarcodeReaded
用此代码替换您的评论。
让 url = NSURL(string: episode.thumbnailURL)!这一行出错了。
@Kopiko 编译时间还是运行时间?
无法转换“NSURL”类型的值?到预期的参数类型“字符串”以上是关于如何在 JSON 中循环数组 imageURL 以在图像视图中显示的主要内容,如果未能解决你的问题,请参考以下文章
如何通过 Postman 以 JSON 格式在请求正文中发送对象数组?
如何循环遍历对象数组中的对象数组并使用 Angular/Ionic 在我的 HTML 中显示?