如何在swift中异步下载图像

时间:2017-03-17 13:58:20

标签: ios asynchronous uiimageview swift2 uicollectionview

您好我正在使用swift2.2开发应用程序从服务器获取数据并将其传递到集合视图。从服务器获取更多图像我无法快速通过它消耗了大量时间所以我需要尽可能快地通过。

我的视图控制器中的代码:

 func jsonParsingFromURL() {

    self.view.makeToastActivity(.Center)
    if Reachability.isConnectedToNetwork() == true {
      Alamofire.request(.POST, "http://something.com=\(appDelCityname)&fromLimit=0&toLimit=20", parameters: nil, encoding: .URL, headers: nil).response {
        (req, res, data, error) - > Void in
          let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print(dataString)

        let json = JSON(data: data!)
        let jsonData = json["ad_count"].int
        if jsonData == 0 {
          let alert = UIAlertController(title: "sorry!", message: "No Ads availabe", preferredStyle: UIAlertControllerStyle.Alert)
          alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
          self.presentViewController(alert, animated: true, completion: nil)
        } else {
          self.startParsing(data!)
        }
      }
    } else {
      let alert = UIAlertController(title: "No Internet Connection", message: "make sure your device is connected to the internet", preferredStyle: UIAlertControllerStyle.Alert)
      alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
      self.presentViewController(alert, animated: true, completion: nil)
    }

  }

  func startParsing(data: NSData) {
    let json = JSON(data: data)
    let mainArr = json["subcategory"].array!
      for item in mainArr {
        self.fetchImage = item["images"].stringValue
        self.fetchPrice = item["originalprice"].stringValue
        self.fetchTitle = item["adtitle"].stringValue
        self.fetchCityname = item["districtname"].stringValue
        let takefirstImg = self.fetchImage.componentsSeparatedByString(",")
        let firstimgofStr = takefirstImg[0]

        dispatch_async(dispatch_get_main_queue(), {
          () - > Void in
          let URL_API_HOST2: String = "https://www.something.com"
          let url = NSURL(string: URL_API_HOST2 + firstimgofStr)
          let data = NSData(contentsOfURL: url!)
          let imageyy = UIImage(data: data!)
          self.priceArr.append(self.fetchPrice)
          self.cityArr.append(self.fetchCityname)
          self.adtitleArr.append(self.fetchTitle)
          print("something = \(firstimgofStr)")
          print("check image = \(self.fetchTitle)")
          self.imageDict.append(imageyy!)
          self.view.hideToastActivity()
        })
        self.refresh()
      }

  }

  func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) - > Int {
    return imageDict.count
  }
  func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) - > UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("FilterCell", forIndexPath: indexPath) as!SecondTableViewCell

    cell.FifTitle.text = adtitleArr[indexPath.item]
    cell.FifAddress.text = cityArr[indexPath.item]
    cell.Fifprice.text = priceArr[indexPath.item]
    dispatch_async(dispatch_get_main_queue(), {

      cell.Fifimage.image = self.imageDict[indexPath.item]

    })

    // cell.Fifimage.sd_setImageWithURL(NSURL(string: URL_API_HOST2 + (firstImage as String)))

    return cell
  }

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

    return imageDict[indexPath.item].size
  }

我有SDWebImage的库但是只允许url类型,但是我必须使用UIImage值来计算图像的大小以获得Pinterest样式视图。根据我的方法它运行良好但是当我从中获得更多价值时它显示的服务器很晚,所以帮助我处理这个过程,从早上起就一直在努力。

0 个答案:

没有答案