[英]Alamofire unexpectedly found nil while unwrapping an Optional value
I use this Alamofire code to download images for URL 我使用此Alamofire代码下载URL的图像
func getImage(imageUrlString: String, completionHandler: (responseObject: UIImage?, error: NSError?) -> ()) {
makeGetImageCall(imageUrlString, completionHandler: completionHandler)
}
func makeGetImageCall(imageUrlString: String, completionHandler: (responseObject: UIImage?, error: NSError?) -> ()) {
//Perform request
print("Trying to get: " + imageUrlString)
Alamofire.request(.GET, imageUrlString, headers: ["Authorization": NSUserDefaults.standardUserDefaults().stringForKey("BasicAuthenticationString")!])
.responseImage { request, response, result in
print(request)
print(response)
print(result)
completionHandler(responseObject: result.value, error: nil)
}
}
This is my class that uses the method: 这是我使用该方法的类:
public class NewsListEntry: NSObject {
public var thumbnail: String = ""
public var thumbnailImage: UIImage = UIImage()
public var thumbnailDownloaded: Bool = false
public func downloadThumbnail() {
print(self.title)
GetImageHandeler().getImage(self.thumbnail, completionHandler: { (responseObject, error) in
})
}
}
Then i get a: 然后我得到一个:
fatal error: unexpectedly found nil while unwrapping an Optional value
What have i done wrong? 我做错了什么?
This is the errors im getting: 这是我得到的错误:
What have i done wrong? 我做错了什么?
Two things. 两件事情。 First, you are using the force-unwrap operator somewhere, possibly here: 首先,您可能在以下位置使用force-wwrap运算符:
NSUserDefaults.standardUserDefaults().stringForKey("BasicAuthenticationString")!
This means you're guaranteeing that the return value isn't nil
, but in this case, it was. 这意味着您保证返回的值不是nil
,但在这种情况下是。 Since you broke your promise, the app crashes. 由于您违背了诺言,因此应用程序崩溃了。
Second, PLEASE DO NOT STORE AUTHORIZATION STRINGS IN NSUSERDEFAULTS . 其次, 请不要在NSUSERDEFAULTS中存储授权字符串 。 iOS has a highly secure keychain for a reason. iOS具有一个高度安全的钥匙串,这是有原因的。 NSUserDefaults
provides no encryption. NSUserDefaults
提供加密。 Please use the keychain. 请使用钥匙扣。 There are wrapper libraries like Locksmith and SSKeychain which can help you. 有包装库,如Locksmith和SSKeychain可以为您提供帮助。
You are unwrapping the result without checking if it's valid or not. 您正在展开结果,而不检查结果是否有效。 Add the following code: 添加以下代码:
Alamofire.request(.GET, imageUrlString, headers: ["Authorization": NSUserDefaults.standardUserDefaults().stringForKey("BasicAuthenticationString")!])
.responseImage { request, response, result in
print(request)
print(response)
print(result)
switch result {
case .Success(let value):
completionHandler(responseObject: value, error: nil)
case .Failure(_, let error):
completionHandler(responseObject: nil, error: error)
}
}
If using Swift 2, you'll need to change the error
parameter of the completionHandler
block from NSError?
如果使用Swift 2,则需要从NSError?
更改completionHandler
块的error
参数NSError?
to ErrorType
. 到ErrorType
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.