【问题标题】:Unable to get data from array无法从数组中获取数据
【发布时间】:2015-10-16 11:30:31
【问题描述】:

我在尝试将数据访问到包含一些图像 URL 的数组时遇到问题。

每次我尝试创建我的图像时,我的应用程序永远不会停止加载,并创建一个循环,顺便说一下我的数组永远不会停止填充。

这是我的代码:

class swipe : UIViewController, KinderDelegate {    

    var urls = [NSURL!]()
    var pictureApp: String!

    func fetchdata(int: Int, completion: (()->())?) {

         for repo in repo {
                    urls.append(NSURL(string: repo.picture_url!)!)
                    dump(repos)
                    i++
                    NSLog("nombre de line = %i", PicArray.count)

                    pictureApp = repo.picture_url
         }

        if let img = imageCache[pictureApp!] {
                    let newCard = Model()
                    newCard.image = img
                    print("image présente")
        }else {

            for url in urls{
               if #available(iOS 8.0, *) {
                  let newCard = Model()
                  dispatch_async(dispatch_get_global_queue(QOS_CLASS_BACKGROUND, 0)) {
                     if let data = NSData(contentsOfURL: url) {
                              let image = UIImage(data: data)!
                              newCard.image = (image: image)
                              dispatch_async(dispatch_get_main_queue()) {
                                        newCard.image
                              }
                     }
                  }
                  self.data.append(newCard)
               }                            
            }
       }

       if self.data.count == 4 {
          completion!()
          return
       } else {
          self.fetchData(0, completion: completion)
       }
   }

}

如何利用数组中的 URL 来创建一些图像?

【问题讨论】:

  • 不应该是for repo in repos
  • 除了 Azzaknight,'repos' 来自哪里?
  • 谢谢你们,实际上我不知道为什么我没有使用我的循环“repo for repos”,我尝试使用它并将我的代码更改为我更新的代码,一切正常,谢谢:)

标签: arrays swift loops url nsdata


【解决方案1】:

就像 Azzaknight 建议的那样,我尝试使用循环“repo for repos”并为此更改了我的代码:

do {
    data = try NSData(contentsOfURL: NSURL(string: repo.picture_url!)!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
     let image = UIImage(data: data!)!
      newCard.image = (image: image)
       dispatch_async(dispatch_get_main_queue()) {
                                        newCard.image
                                    }
                                }
                                catch {
                                    print("Handle \(error) here")
                                }
                       }
              }
              self.data.append(newCard)
           }       

现在一切正常!

【讨论】:

    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    • 1970-01-01
    • 2021-12-07
    相关资源
    最近更新 更多