[英]Swift unwrapping optional giving error with data
My iOS application fetch data from server and render some images from that data using 'Kingfisher', the problem is whenever i add or replace new image on server application crashes due to this code below with error : " fatal error: unexpectedly found nil while unwrapping an Optional value " 我的iOS应用程序从服务器获取数据并使用'Kingfisher'渲染数据中的某些图像,问题是,每当我在服务器应用程序上添加或替换新图像时,由于以下代码而崩溃,并显示以下错误:“ 致命错误:展开包装时意外发现nil可选值 “
let prfix:String = "MY_PREFIX_URL /\(org.image)"
celImage.kf_setImageWithURL((NSURL(string: prfix))!)
Please check the sceeenshot for more detail 请检查场景截图以获取更多详细信息
I don't undestand why I am getting this error, because you can see
prfix
got a value. 我不理解为什么我会收到此错误,因为您可以看到
prfix
获得了价值。
I think its due to prefix
contain with unnecessary characters, you can fix this with URLHostAllowedCharacterSet
我认为由于
prefix
包含不必要的字符,您可以使用URLHostAllowedCharacterSet
修复此URLHostAllowedCharacterSet
You can fix prefix
malformed url like this (swift 2.x). 您可以这样修改
prefix
格式错误的url(swift 2.x)。
let urlStr : NSString = prfix.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
celImage.kf_setImageWithURL((NSURL(string: urlStr as String))!)
this will make sure the url contains only good string. 这样可以确保网址仅包含正确的字符串。
NSURL(string:)
is a failable initialiser and can then return nil
if your string
parameter is not a valid URL, as you can read in the documentation of NSURL: NSURL(string:)
是一个失败的初始化程序,如果您的string
参数不是有效的URL,则可以返回nil
,您可以在NSURL文档中阅读:
Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.
You have to check your final URL integrity because apparently it is malformed... 您必须检查最终的URL完整性,因为它显然格式不正确...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.