我正在尝试使用 NSURLSession 加载图像。 如果响应返回 200 以外的状态代码,我该如何“停止”NSURLSession?我想显示网络问题弹出窗口。
class ViewController: UIViewController {
override func viewDidLoad()
{
super.viewDidLoad()
loadData()
}
func loadData()
{
self.downloadFullImageFrom("https://www.google.fr/logos/doodles/2015/holidays-2015-day-3-6399865393250304-5649050225344512-ror.jpg") { image in
dispatch_async(dispatch_get_main_queue())
{
//DO SOMETHING WITH images IF DOWNLOAD IS OK
//HOW CAN I KNOW IF dataTaskWithURL FAILED?
}
}
}
func downloadFullImageFrom(url:String, completion: ((image: UIImage?) -> Void)) {
let task = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in
if let httpResponse = response as? NSHTTPURLResponse
{
if httpResponse.statusCode == 200
{
completion(image: UIImage(data: data!))
}
else { return }
}
}
task.resume()
}
}
最佳答案
尝试使用 guard 来解包你的可选值并添加 where 子句来控制预期结果,如果失败则返回 nil:
func loadData() {
downloadFullImageFrom("https://www.google.fr/logos/doodles/2015/holidays-2015-day-3-6399865393250304-5649050225344512-ror.jpg") { image in
dispatch_async(dispatch_get_main_queue()) {
guard let image = image else {
print("error loading image")
return
}
//DO SOMETHING WITH images IF DOWNLOAD IS OK
print(image.size)
}
}
}
func downloadFullImageFrom(link: String, completion: ((image: UIImage?) -> Void)) {
guard let url = NSURL(string: link) else {
completion(image: nil)
return
}
NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response , error) in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let data = data, image = UIImage(data: data) where error == nil else {
// display a network issue pop up
print("======= statusCode =======")
print((response as? NSHTTPURLResponse)?.statusCode)
completion(image: nil)
return
}
completion(image: image)
}.resume()
}
Xcode 8.3.1 • Swift 3.1
func loadData() {
downloadFullImageFrom(link: "https://www.google.fr/logos/doodles/2015/holidays-2015-day-3-6399865393250304-5649050225344512-ror.jpg") { image in
DispatchQueue.main.async() {
guard let image = image else {
print("error loading image")
return
}
//DO SOMETHING WITH images IF DOWNLOAD IS OK
print(image.size)
}
}
}
func downloadFullImageFrom(link: String, completion: @escaping ((UIImage?) -> Void)) {
guard let url = URL(string: link) else {
completion(nil)
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse,
httpURLResponse.statusCode == 200,
let data = data,
let image = UIImage(data: data),
error == nil
else {
// display a network issue pop up
print("======= statusCode =======")
print((response as? HTTPURLResponse)?.statusCode ?? "")
completion(nil)
return
}
completion(image)
}.resume()
}
关于ios - 如果响应返回 200 以外的状态代码,是否停止我的 NSURLSession?在 SWIFT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34465979/
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has
为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返
我希望我的UserPrice模型的属性在它们为空或不验证数值时默认为0。这些属性是tax_rate、shipping_cost和price。classCreateUserPrices8,:scale=>2t.decimal:tax_rate,:precision=>8,:scale=>2t.decimal:shipping_cost,:precision=>8,:scale=>2endendend起初,我将所有3列的:default=>0放在表格中,但我不想要这样,因为它已经填充了字段,我想使用占位符。这是我的UserPrice模型:classUserPrice回答before_val
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我有一个这样的哈希数组:[{:foo=>2,:date=>Sat,01Sep2014},{:foo2=>2,:date=>Sat,02Sep2014},{:foo3=>3,:date=>Sat,01Sep2014},{:foo4=>4,:date=>Sat,03Sep2014},{:foo5=>5,:date=>Sat,02Sep2014}]如果:date相同,我想合并哈希值。我对上面数组的期望是:[{:foo=>2,:foo3=>3,:date=>Sat,01Sep2014},{:foo2=>2,:foo5=>5:date=>Sat,02Sep2014},{:foo4=>4,:dat
我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案
这里有一个很好的答案解释了如何在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返回它复制的字节数,但是当我还没有下
我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie
我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru