如何在JSON中循环数据当标签中的字符串等于JSON数组中的数据时

时间:2016-09-01 07:15:12

标签: arrays json swift loops

我需要在标签上显示来自JSON的数据。但是我的代码得到了错误。请帮我看一下函数barcodeReaded。如何在数组JSON文件的“testCode”中标签等于字符串中的String时循环数据。

此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 UIKit

class barcodeViewController: UIViewController, BarcodeDelegate {


    @IBOutlet weak var thumbnailImageView: UIImageView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var drugLabel: UILabel!
    @IBOutlet weak var priceLabel: UILabel!
    @IBOutlet weak var showCodeLabel: UILabel!


    var episode: Episode!

    override func viewDidLoad() {
        super.viewDidLoad()


    }

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

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        print("Segue!")

        let barcodeViewController: barcodeCapViewController = segue.destinationViewController as! barcodeCapViewController
        barcodeViewController.delegate = self

    }

    @IBAction func doneButtonPressed(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }


    func barcodeReaded(barcode: String) {
        print("Barcode is: \(barcode)")
        showCodeLabel.text = barcode
        barcode = episode.testCode

        if((episode.testCode) != nil)
        {
            titleLabel.text = episode.title
            drugLabel.text = episode.drug
            priceLabel.text = episode.price
        }


      }

}








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
  } 
 }

This interface image

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中使用的图像

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
            })
        })
    }
}

2 个答案:

答案 0 :(得分:0)

您可以从字典数组中获取此条形码的详细信息。

func barcodeReaded(barcode: String) {
    print("Barcode is: \(barcode)")
    showCodeLabel.text = barcode
    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
    }   
}

答案 1 :(得分:0)

试试吧。希望它可以帮到你。

var resultData = NSDictionary()
var episode = NSArray()

func loadDataFromJSON(){
    // put your json to resultData 
    // Now resultData holds whole json object
    // get episode array from resultData

    episode = resultData.objectForKey("episode") as! NSArray
}

func traverseThroughEpisode(){

    for i in 0..< episode.count {
        // retrive testCode like that & set it whatever you want
        let testCode = episode.objectAtIndex(i).objectForKey("testCode") as! String
    }
}