2017-02-14 21 views
0

私のコードに問題があります。画像のURLを取得するレベルまでJSONを解析しました。私は、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に設定しようとしていますか? –

+0

JSON結果には取得しようとしているjpegイメージのURLが含まれています。私のコードはJSONを解析してURLに到達します。 URLを抽出できないので、画像を表示できるようにUIimageViewを含むcollectionViewcellを生成するためにURLを使用できます。アドバイスはありますか? – Ingelbert

+0

私の答えをチェックしてください私はあなたが知る必要があるすべてを更新しました。 –

答えて

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実際の画像URLが必要です。

EDIT:(コメントであなたの質問に基づいて)

1:あなたがNSDictionary JSON Responeを取得します。

2:

3:そのNSArrayの中にあなたがNSDictionaryで各画像オブジェクトのための一つのオブジェクトを持っている:Insideは、NSDictionaryあなたは、 "アイテム"、( "アイテム" objectForKey)でNSArrayを取得します。

4最後に、各画像オブジェクトNSDictionaryには、画像の最終URLである "media"(objectForKey: "media")という名前のURLがあります。その後、そのURLに基​​づいてUIImageをダウンロードする必要があります

私はあなたに間違ったコードの例を与えたくありませんので、There are many threads JSONレスポンスからURLまたは任意の値を取得する方法はありません。

+0

他のスレッドのどの部分を具体的にお考えですか?どのようにURLを集めてダウンロードできるのかあなたがリンクに添付したもののいくつかを読んでいましたが、私はリンクが説明していたプロセスを理解していません。 – Ingelbert

+0

あなたは私が応答について書いたものを読むべきです。最初に 'NSDictionary' JSON Responeを取得します。 'NSDictionary'の中には、「items」のNSArrayがあります。その 'NSArray'の中には、各画像のための一つのオブジェクトがあります。これは' NSDictionary'です。最後に、各画像オブジェクト 'NSDictionary'には、画像への最後の' URL 'である "url" 'objectForKey'" media "があります。その後、そのURLに基​​づいて 'UIImage'をダウンロードする必要があります。 –

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

コードに少なくとも2つのサードパーティのライブラリが必要です。 – vadian

+0

@vadianはいすべてのライブラリファイルがプロジェクトにあります。添付されたリンクを確認してください –

関連する問題