2017-02-14 134 views
0

我有我的代碼問題,我已經解析出我的JSON到我得到圖像的URL的級別。我正在嘗試使用URL給我的圖像在集合視圖單元格中填充圖像視圖。這是我的代碼。解析JSON並提取圖像的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 
    } 

} 
+0

JSON是不是一個圖像。 cell.imageView.image = media [indexPath.item] as? UIImage,你正試圖設置一個JSON值到UIImage? – 2017-02-14 00:25:01

+0

JSON結果包含我嘗試獲取的jpeg圖像的URL,我的代碼將解析JSON以獲取該URL。我無法提取網址,因此我可以使用它來填充包含UIimageView的collectionViewcell,以便我可以查看圖像。你有什麼建議嗎? – Ingelbert

+0

檢查我的答案我已更新所有你需要知道的。 – 2017-02-14 00:42:59

回答

1

您的JSON響應不是圖像。

cell.imageView.image = media[indexPath.item]as? UIImage,您正嘗試將JSON值設置爲UIImage。

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

此URL返回與URL's實際圖像 JSON的響應。

然後您需要download the UIImage那些實際圖片網址

編輯:(基於評論你的問題)

1:你得到NSDictionary輸入反應JSON。

2:裏面的NSDictionary你得到一個NSArray與 「項目」,(objectForKey: 「項目」)

3:內部的NSArray你必須爲每個圖像對象,這是一個NSDictionary一個對象。

4:最後,在每個圖像對象NSDictionary中都有一個名爲「media」(objectForKey:「media」)的url,它是圖像的最終URL。然後你需要下載基於該URL的UIImage

我不在Swift中編碼,所以我不想給你錯誤的代碼示例There are many threads如何從JSON響應中獲取URL或任何值。

+0

你的意思是什麼其他線程?你將如何收集這些URL,以便你可以下載它們。我正在閱讀鏈接中的一些內容,我不明白鏈接解釋的過程。 – Ingelbert

+0

你應該閱讀我寫的關於響應的內容。首先你得到'NSDictionary' JSON Respone。在'NSDictionary'裏面你得到一個「NSArray」的「items」。在'NSArray'裏面,每個圖像都有一個對象,它是一個'NSDictionary'。最後,在每個圖像對象'NSDictionary'中都有一個「url」'objectForKey'「媒體」,它是您圖像的最終'URL'。然後你需要下載基於該URL的'UIImage'。 – 2017-02-14 00:54:54

0

試試這個代碼,你會得到你預期的輸出

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?) { 

    } 
    */ 

} 

我還附上了鏈接,你會發現項目here

+0

您應該提及代碼至少需要兩個第三方庫 – vadian

+0

@vadian是所有庫文件都在我附加的項目中鏈接檢查出來 –