jjzjj

ios - 从 URL 下载图像并作为图像添加到数组

coder 2024-01-30 原文

这就是我想要做的:

  1. Query from Parse.com (PFFile to array - strings stored in array as .png link)
  2. Download the images from array using Haneke to a array of images
  3. Set the first image to a UIImageView.
  4. When tapping the UIImageView, I want to change to the next image.

问题是在我点击 UIImageView 之前图像不会显示,当我点击以尝试更改图像时,一直显示相同的 UIImage。

这是我的 ViewController 代码的样子:

import UIKit
import Parse

class ViewController: UIViewController {

    var userFile = [PFFile]()
    var createdAt = [NSDate]()
    var objID = [String]()

    var countInt = 0

    @IBOutlet var imageView: UIImageView!

    var imageArray: [UIImageView] = []
    let imageToArray = UIImageView()

    override func viewDidLoad() {
        super.viewDidLoad()

        imageToArray.frame.size = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height)

        queryStory()

        let tap = UITapGestureRecognizer(target: self, action: #selector(handleTap))
        imageView.addGestureRecognizer(tap)
        imageView.userInteractionEnabled = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func downloadImages() {
        if (countInt <= userFile.count - 1){
            imageToArray.hnk_setImageFromURL(NSURL(string: userFile[countInt].url!)!)
            countInt = countInt + 1
            imageArray.insert(imageToArray, atIndex: 0)
            print("Image downloaded. Current count: \(imageArray.count)")
            self.downloadImages()
        }
        else{
            print("no more items")
            countInt = 0
            setImage()
        }

    }

    func setImage() {
        imageView.image = imageArray[countInt].image
        countInt = countInt + 1
        print("setImage set")
    }

    func handleTap(gestureRecognizer: UIGestureRecognizer)
    {
        print("tapped")

        if (countInt <= imageArray.count - 1){
            imageView.image = nil
            print("set new image")
            imageView.image = imageArray[countInt].image
            countInt = countInt + 1
        }
        else{
            print("no more items")
        }
    }

    func queryStory(){
        self.userFile.removeAll()
        self.objID.removeAll()
        self.createdAt.removeAll()

        let query = PFQuery(className: "myClass")
        query.orderByDescending("createdAt")

        query.findObjectsInBackgroundWithBlock { (posts: [PFObject]?, error: NSError?) -> Void in
            if (error == nil){
                // Success fetching objects

                print("Post count:", posts!.count)

                for post in posts! {

                    if let imagefile = post["userFile"] as? PFFile {
                        self.userFile.append(post["userFile"] as! PFFile)
                        self.objID.append(post.objectId!)
                        self.createdAt.append(post.createdAt!)
                    }
                }

                dispatch_async(dispatch_get_main_queue()) {
                    print("Done")
                    self.downloadImages()
                }

                print("Uploaded files count: ", self.userFile.count)
            }
            else{
                print(error)

                let alert = UIAlertView()
                alert.title = "Error"
                alert.message = error?.localizedDescription
                alert.addButtonWithTitle("OK")
                alert.show()
            }
        }
    }
}

几个小时以来,我一直在努力解决这个问题 - 但还是做不到。

这是我点击 UIImage 后的完整输出:

Post count: 8
Uploaded files count:  8
Post count: 8
Uploaded files count:  8
Done
Image downloaded. Current count: 1
Image downloaded. Current count: 2
Image downloaded. Current count: 3
Image downloaded. Current count: 4
Image downloaded. Current count: 5
Image downloaded. Current count: 6
Image downloaded. Current count: 7
Image downloaded. Current count: 8
no more items
setImage set
tapped
set new image

编辑:奇怪...当我在 tapGesture 函数中运行 print(imageArray.description) 时,我得到以下输出:http://pastebin.com/H0u97pz5

最佳答案

我认为问题在于 imageToArray 是一个常量。尝试:

func downloadImages() {
    if (countInt <= userFile.count - 1){
        var imageToInsert = UIImageView()
        imageToInsert.hnk_setImageFromURL(NSURL(string: userFile[countInt].url!)!)
        countInt = countInt + 1
        imageArray.insert(imageToInsert, atIndex: 0)
        print("Image downloaded. Current count: \(imageArray.count)")
        self.downloadImages()
    }
    else{
        print("no more items")
        countInt = 0
        setImage()
    }

关于ios - 从 URL 下载图像并作为图像添加到数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927056/

有关ios - 从 URL 下载图像并作为图像添加到数组的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  3. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  4. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  5. ruby - 将 Bootstrap Less 添加到 Sinatra - 2

    我有一个ModularSinatra应用程序,我正在尝试将Bootstrap添加到应用程序中。get'/bootstrap/application.css'doless:"bootstrap/bootstrap"end我在views/bootstrap中有所有less文件,包括bootstrap.less。我收到这个错误:Less::ParseErrorat/bootstrap/application.css'reset.less'wasn'tfound.Bootstrap.less的第一行是://CSSReset@import"reset.less";我尝试了所有不同的路径格式,但它

  6. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  7. ruby-on-rails - rails : save file from URL and save it to Amazon S3 - 2

    从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex

  8. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  9. ruby - 续集在添加关联时访问many_to_many连接表 - 2

    我正在使用Sequel构建一个愿望list系统。我有一个wishlists和itemstable和一个items_wishlists连接表(该名称是续集选择的名称)。items_wishlists表还有一个用于facebookid的额外列(因此我可以存储opengraph操作),这是一个NOTNULL列。我还有Wishlist和Item具有续集many_to_many关联的模型已建立。Wishlist类也有:selectmany_to_many关联的选项设置为select:[:items.*,:items_wishlists__facebook_action_id].有没有一种方法可以

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐