繁体   English   中英

解析JSON并提取图像的URL

[英]Parsing JSON and extracting URLS for images

我的代码有问题,我已经将JSON解析为获取图像URL的级别。 我正在尝试使用URL给我的图像填充集合视图单元格中的图像视图。 这是我的代码。

import UIKit

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

    var media = NSDictionary()

    @IBAction func SearchBTN(_ sender: AnyObject) {
        getPictures()

    }
    @IBOutlet weak var CollectionView: UICollectionView!
    @IBOutlet weak var searchBoxTF: UITextField!



    func getPictures(){
        let url = URL(string: "http://www.flickr.com/services/feeds/photos_public.gne?tags=baseball&format=json&nojsoncallback=1")
        let session = URLSession(configuration: URLSessionConfiguration.default)
        let task = URLSession.shared.dataTask(with: url!){(data, response, error) in
            if error != nil
            {
                print("Error")
            }
            else
            {
                if let content = data
                {
                    do
                    {
                        let myJSON = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as? AnyObject
                    //print(myJSON)
                        if let images = myJSON?["items"] as? [[String: AnyObject]]
                        {
                            var media = UIImage()
                            for media in images
                            {
                               // let media = self.media
                                print(media["media"])

                            }


                        }
                    }

                    catch
                    {

                    }
                }
            }
        }
        task.resume()
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        CollectionView.delegate = self
        CollectionView.dataSource = self
        // Do any additional setup after loading the view, typically from a nib.
    }

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


    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return media.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! ImageCollectionViewCell
        cell.imageView.image = media[indexPath.item]as? UIImage
        return cell
    }

}

您的JSON响应不是图像。

cell.imageView.image = media[indexPath.item]as? UIImage cell.imageView.image = media[indexPath.item]as? UIImage ,您正在尝试为cell.imageView.image = media[indexPath.item]as? UIImage设置JSON值。

http://www.flickr.com/services/feeds/photos_public.gne?tags=baseball&format=json&nojsoncallback=1

此URL返回JSON对具有实际图像的 URL's响应。

然后,您需要从那些实际的图像URL 下载UIImage

编辑:(基于您在评论中的问题)

1:您将获得NSDictionary JSON Respone。

2:在NSDictionary内部,您将获得一个带有“ items”的NSArray ,(objectForKey:“ items”)

3:在该NSArray ,每个图像对象都有一个对象,即NSDictionary

4:最后,在每个图像对象NSDictionary都有一个名为“ media”的URL(objectForKey:“ media”),它是图像的最终URL。 然后您需要根据该URL下载UIImage

我没有用Swift编写代码,所以我不想给您错误的代码示例, 有很多线程如何从JSON响应中获取URL或任何值。

试试这个代码,您将获得预期的输出

import UIKit

private let reuseIdentifier = "Cell"

class MCollectionViewController: UICollectionViewController {

    var arraImage: [String] = [String]()


    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        self.collectionView!.backgroundColor = UIColor.whiteColor()
        RestAPIManager.sharedInstance.getServerData { (Json) -> Void in
            //print("Response = \(Json)")
            let array = Json["items"].arrayValue
            for item in array {
                print("\(item["media"]["m"])")
                self.arraImage.append(item["media"]["m"].stringValue)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.collectionView!.reloadData()
                })
            }
        }
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return arraImage.count
    }

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {

        let padding =  10
        let collectionViewSize = collectionView.frame.size.width - CGFloat(padding)

        return CGSizeMake(collectionViewSize/2, collectionViewSize/2)

    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

        if let url: NSURL = NSURL(string: arraImage[indexPath.row]) {
            cell.imageView.sd_setImageWithURL(url)
        }
        return cell
    }

    // MARK: UICollectionViewDelegate

    /*
    // Uncomment this method to specify if the specified item should be highlighted during tracking
    override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment this method to specify if the specified item should be selected
    override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return true
    }
    */

    /*
    // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
    override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
        return false
    }

    override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {

    }
    */

}

我还附上了链接,您可以在此处找到该项目

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM