【问题标题】:Images keep on reloading in collection view cell in swift图像继续快速重新加载到集合视图单元中
【发布时间】:2015-12-27 09:22:21
【问题描述】:

我是 Swift 新手,我想使用 Instagram API 加载我的 Instagram 图片。 我成功了,但是当我在模拟器中向下滚动时,图像会不断重新加载和改变位置。我错过了什么?

这是我的代码:

PhotosViewController.swift:

 import UIKit
 import OAuthSwift

 class PhotosViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {

    //var array:[String] = []
    var photos:NSArray = []

    var accessToken:NSString!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        //array = ["Treehouse"]
        self.title = "InstaManage"

        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(106.0, 106.0)
        layout.minimumInteritemSpacing = 1.0
        layout.minimumLineSpacing = 1.0

        collectionView?.collectionViewLayout = layout


        collectionView!.backgroundColor = UIColor.whiteColor()

        let userDefaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
        self.accessToken = userDefaults.stringForKey("accessToken")
        let oauthswift = OAuth2Swift(
            consumerKey:    "abcde",
            consumerSecret: "jafkaffjafkl",
            authorizeUrl:   "https://api.instagram.com/oauth/authorize",
            responseType:   "token"
        )

        if (self.accessToken == nil) {
            oauthswift.authorizeWithCallbackURL(NSURL(string: "authcheck://auth/instagram")!, scope: "public_content", state: "INSTAGRAM", success: { (credential, response, parameters) -> Void in

                print(credential.oauth_token)
                self.accessToken = credential.oauth_token
                userDefaults.setObject(self.accessToken, forKey: "accessToken")
                userDefaults.synchronize()
                },
                failure: { error in
                    print(error.localizedDescription)
                }

            )

        } else {
            self.downloader()
        }
}

func downloader() {
    let config:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session:NSURLSession = NSURLSession(configuration: config)
    let urlString: NSString = NSString(string: "https://api.instagram.com/v1/users/self/media/recent/?access_token=\(self.accessToken)")
    let url:NSURL = NSURL(string: urlString as String)!
    let request:NSURLRequest = NSURLRequest(URL: url)
    let task = session.downloadTaskWithRequest(request) { (location, response, error) -> Void in


        let data:NSData = NSData(contentsOfURL: location!)!
        do {

            let responseDictionary:NSDictionary = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
            //print(responseDictionary)
            self.photos = responseDictionary.valueForKeyPath("data") as! NSArray

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                self.collectionView?.reloadData()
            })

            //print(self.photos)
        } catch {
            print(error)
        }
    }


    task.resume()

}




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


// 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 self.photos.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! PhotosViewCell

    cell.backgroundColor = UIColor.brownColor()

    //cell.imageView!.image = UIImage(named: array[0])
    //let photo = photos[indexPath.row]
    //let url1 = photo.valueForKeyPath("images.standard_resolution.url") as! String
    //cell.url1 = url1

    cell.photo = self.photos[indexPath.row] as! NSDictionary
    cell.url1 = (cell.photo.valueForKeyPath("images.standard_resolution.url"))! as! String
    //print(cell.url1)
    // Configure the cell

    return cell
}

PhotosViewCell.swift:

 import UIKit

 class PhotosViewCell: UICollectionViewCell {

@IBOutlet weak var imageView: UIImageView!
var url1:String = "" {
    didSet {
        let url:NSURL = NSURL(string: url1)!
        //print(url)
        downloadFromUrl(url)
    }
}

var photo:NSDictionary = NSDictionary()

override func layoutSubviews() {
    self.imageView?.frame = self.contentView.bounds
}


func downloadFromUrl(url: NSURL) {
    let config:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
    let session:NSURLSession = NSURLSession(configuration: config)
    let request:NSURLRequest = NSURLRequest(URL: url)
    let task = session.downloadTaskWithRequest(request) { (location, response, error) -> Void in


        let data:NSData = NSData(contentsOfURL: location!)!
        let image:UIImage = UIImage(data: data)!

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            self.imageView.image = image
        })
    }


    task.resume()


}

}

【问题讨论】:

    标签: ios iphone xcode swift instagram-api


    【解决方案1】:

    问题是每次单元格出现在屏幕上都会触发downloadFromUrl方法,你必须缓存下载的图片,而不是每次都尝试下载。

    【讨论】:

    • 我也这么想。我稍后会尝试,然后我会回复。谢谢
    • 思想缓存解决了它,但它只解决了图像问题。单元格仍会重新加载,从而重新加载网址,因此无法检索相应的网址。
    • 如果图片被缓存了,你就不需要更多的url了。
    【解决方案2】:

    听起来像是单元重用问题。 当您滚动时,Collection View 会重用他已经加载到内存中的单元格以节省内存并使一切变得更加快捷。 我相信在您的自定义单元格中实施方法prepareForReuse 将解决您的问题。使用它来取消此单元格已有的图像和 URL,如下所示:

    override func prepareForReuse() {
        super.prepareForReuse()
        imageView = nil
        photo = nil
    }
    

    【讨论】:

    • 感谢您的帮助,但它不起作用,因为 nil 不能分配给字典。即使删除了那条线,它仍然没有工作。
    猜你喜欢
    • 2021-01-31
    • 1970-01-01
    • 2018-01-11
    • 2018-08-13
    • 1970-01-01
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    相关资源
    最近更新 更多