草庐IT

ios - UIImageView 的图像加载最多需要 10 秒

coder 2023-09-17 原文

我的 Swift 代码有问题。我想将本地镜像加载到 ImageView 中。这很好用。但是当我模拟应用程序时,您只能在 10-15 秒后看到图像,我找不到问题所在。

这里是图片的代码:

let image = UIImage(named: "simple_weather_icon_01");

weatherIcon.image = image;

self.activityIndicatorView.stopAnimating()

编辑:

override func viewDidLoad() {
    super.viewDidLoad()

    get_data_from_url("myURL")
}

func get_data_from_url(url:String) {
    let url = NSURL(string: url)
    let urlRequest = NSMutableURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 15.0)
    let queue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(urlRequest, queue: queue, completionHandler: {response, data, error in
            if data!.length > 0 && error == nil {
                let json = NSString(data: data!, encoding:  
                NSASCIIStringEncoding)
                self.extract_json(json!)
            } else if data!.length == 0 && error == nil {
                print("Nothing was downloaded1")
            } else if error != nil {
                print("Error happened = \(error)")
            }
        }
    )
}


func extract_json(data:NSString) {
    let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!

    do {
        let json: NSDictionary! = try 
        NSJSONSerialization.JSONObjectWithData(jsonData, options: 
        .AllowFragments) as! NSDictionary

        let result = (json["weather"] as! [[NSObject:AnyObject]])[0]

        let aktIcon = result["icon"] as! String

        if aktIcon == "01d"{
            let image = UIImage(named: "simple_weather_icon_01");

            weatherIcon.image = image;

            self.activityIndicatorView.stopAnimating()

            UIView.animateWithDuration(2.0, delay: 0, options: [.Repeat, 
            .CurveEaseInOut], animations: {
                self.weatherIcon.transform = 
                CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 
                180.0)
            }, completion: nil)
        }
    }
    catch let error as NSError {

    }
}

我必须对图像做些什么吗?

最佳答案

您的问题是您在 UI 线程之外(在某个任意回调线程上)执行了大量与 UI 相关的代码,这意味着 UI 更改不会立即生效,而是在稍后的某个时间点(未明确定义) ).

你要做的就是在主线程上通过以下方式执行UI相关代码:

dispatch_async(dispatch_get_main_queue(),{
    // your ui code here
})

您可以在主线程上执行整个 extract_json 或仅执行相关代码。第二种选择可能更好,因为它对主线程造成的负载稍少。

1。整个 extract_json

你必须用

替换self.extract_json(json!)
dispatch_async(dispatch_get_main_queue(),{
    extract_json(json!)
})

2。只有 UI 代码:

像这样包装 UI 代码:

dispatch_async(dispatch_get_main_queue(),{
    let image = UIImage(named: "simple_weather_icon_01");

    weatherIcon.image = image;

    self.activityIndicatorView.stopAnimating()

    UIView.animateWithDuration(2.0, delay: 0, options: [.Repeat, 
        .CurveEaseInOut], animations: {
        self.weatherIcon.transform = 
        CGAffineTransformMakeRotation((180.0 * CGFloat(M_PI)) / 
            180.0)
    }, completion: nil)
})

关于ios - UIImageView 的图像加载最多需要 10 秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32296295/

有关ios - UIImageView 的图像加载最多需要 10 秒的更多相关文章

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

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

  2. ruby - 如何以所有可能的方式将字符串拆分为长度最多为 3 的连续子字符串? - 2

    我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123

  3. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  4. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

  5. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  6. ruby - RuntimeError(自动加载常量 Apps 多线程时检测到循环依赖 - 2

    我收到这个错误:RuntimeError(自动加载常量Apps时检测到循环依赖当我使用多线程时。下面是我的代码。为什么会这样?我尝试多线程的原因是因为我正在编写一个HTML抓取应用程序。对Nokogiri::HTML(open())的调用是一个同步阻塞调用,需要1秒才能返回,我有100,000多个页面要访问,所以我试图运行多个线程来解决这个问题。有更好的方法吗?classToolsController0)app.website=array.join(',')putsapp.websiteelseapp.website="NONE"endapp.saveapps=Apps.order("

  7. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  8. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  9. ruby-on-rails - 使用 config.threadsafe 时从 lib/加载模块/类的正确方法是什么!选项? - 2

    我一直致力于让我们的Rails2.3.8应用程序在JRuby下正确运行。一切正常,直到我启用config.threadsafe!以实现JRuby提供的并发性。这导致lib/中的模块和类不再自动加载。使用config.threadsafe!启用:$rubyscript/runner-eproduction'pSim::Sim200Provisioner'/Users/amchale/.rvm/gems/jruby-1.5.1@web-services/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in`co

  10. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

随机推荐