Alamofire unexpectedly found nil while unwrapping an Optional value - ios

I use this Alamofire code to download images for 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:
NSUserDefaults.standardUserDefaults().stringForKey("BasicAuthenticationString")!
This means you're guaranteeing that the return value isn't nil, but in this case, it was. Since you broke your promise, the app crashes.
Second, PLEASE DO NOT STORE AUTHORIZATION STRINGS IN NSUSERDEFAULTS. iOS has a highly secure keychain for a reason. NSUserDefaults provides no encryption. Please use the keychain. There are wrapper libraries like Locksmith and SSKeychain which can help you.

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? to ErrorType.

Related

Migration Alamofire 4 to 5 build issue

I am doing migration after 2 years a lots things have been changed, now flagging a lots of error while building. Most are related to Alamofire 5. Now there are many error keeps coming fixing one by one.
Error: // ERROR: Cannot specialize non-generic type
public static func ObjMappingSerializer<T: Mappable>(_ keyPath: String?) -> DataResponseSerializer<T> { 'DataResponseSerializer'
return DataResponseSerializer { request, response, data, error in
//LogResponse(response, data: data, error: error)
Logger._reqresLogger.logResponse(response, data: data, error: error)
guard error == nil else {
return .failure(parseErrorResponse(data: data, response: response, errorType: error!))
}
guard let _ = data else {
return .failure(errorForNilData())
}
let JSONToMap = deserializeJSON(request: request, response: response, data: data, error: error, keyPath: keyPath)
if let json = JSONToMap as? [String:Any], let parsedObject = Mapper<T>().map(JSON:json) {
return .success(parsedObject)
}
let errorCode = response?.statusCode ?? NSURLErrorCannotParseResponse
return .failure(APIError(code: errorCode, errorUserInfo: nil))
}
}
Fixed by autosuggestion however next error comes
Error: Trailing closure passed to parameter of type 'DataPreprocessor' that does not accept a closure
public static func ObjMappingSerializer(_ keyPath: String?) -> DataResponseSerializer {
return DataResponseSerializer { request, response, data, error in
//LogResponse(response, data: data, error: error)
Logger._reqresLogger.logResponse(response, data: data, error: error)
guard error == nil else {
return .failure(parseErrorResponse(data: data, response: response, errorType: error!))
}
guard let _ = data else {
return .failure(errorForNilData())
}
let JSONToMap = deserializeJSON(request: request, response: response, data: data, error: error, keyPath: keyPath)
if let json = JSONToMap as? [String:Any], let parsedObject = Mapper<T>().map(JSON:json) {
return .success(parsedObject)
}
let errorCode = response?.statusCode ?? NSURLErrorCannotParseResponse
return .failure(APIError(code: errorCode, errorUserInfo: nil))
}
}
Now in Alamofire many methods have been removed in Alamofire 5. How can I fix these errors?
You can no longer initialize a DataResponseSerializer with a closure. I suggest you reevaluate your parsing needs and rebuild around responseDecodable. If you need, you can create your own serializer by adopting ResponseSerializer. Your logic would be the same, just copied into the parse method.

Swift 4 Parse Server Cloud Code Error [duplicate]

PFCloud.callFunctionInBackground("hello", withParameters: ["test":"tester"]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error!.description)
}
}
I am getting the error:
Cannot convert value of type '(AnyObject?, NSError?) -> Void' to
expected argument type 'PFIdResultBlock?' (aka
'Optional<(Optional, Optional) -> ()>')
Even if I add as! PFIdResultBlock, the error will not go away.
How can I go about fixing this?
I definitely appreciate your help on this one!!
There is no need to specify the variable types while implementing the closure (Block in Objective-C) unlike Objective-C. You just need to change your code to the following:
PFCloud.callFunction(inBackground: "",
withParameters: ["": ""]) { (response, error) in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error?.localizedDescription)
}
}

Parse Cloud with Swift PFIdResultBlock Error

PFCloud.callFunctionInBackground("hello", withParameters: ["test":"tester"]) {
(response: AnyObject?, error: NSError?) -> Void in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error!.description)
}
}
I am getting the error:
Cannot convert value of type '(AnyObject?, NSError?) -> Void' to
expected argument type 'PFIdResultBlock?' (aka
'Optional<(Optional, Optional) -> ()>')
Even if I add as! PFIdResultBlock, the error will not go away.
How can I go about fixing this?
I definitely appreciate your help on this one!!
There is no need to specify the variable types while implementing the closure (Block in Objective-C) unlike Objective-C. You just need to change your code to the following:
PFCloud.callFunction(inBackground: "",
withParameters: ["": ""]) { (response, error) in
if error == nil {
let responseString = response as? String
print(responseString)
} else {
print(error?.localizedDescription)
}
}

Alamofire Use of undeclared type 'Serializer'

I have updated to XCode 7 beta 6 and Alamofire needed to be updated to beta 3. In doing so, I'm having to update areas of the code that use Alamofire. One area in particular that I'm having difficulty updating is the code which is used to retrieve an image from a specified URL and load it into a UIImageView.
Previously, the extension for Alamofire that handled that was:
extension Alamofire.Request {
class func imageResponseSerializer() -> Serializer {
return { request, response, data in
if data == nil {
return (nil, nil)
}
let image = UIImage(data: data!, scale: UIScreen.mainScreen().scale)
return (image, nil)
}
}
func responseImage(completionHandler: (NSURLRequest, NSHTTPURLResponse?, UIImage?, NSError?) -> Void) -> Self {
return response(serializer: Request.imageResponseSerializer(), completionHandler: { (request, response, image, error) in
completionHandler(request!, response, image as? UIImage, error)
})
}
}
But not that is throwing the error
Use of undeclared type 'Serializer'
I do realize that Alamofire doesn't use Serializer anymore, but does anyone know where I can find some documentation or examples what to do now when retrieving images?
As you can find in the readme the serialization was rewritten.
You shoudl be able to use the method below:
public protocol ResponseObjectSerializable {
init?(response: NSHTTPURLResponse, representation: AnyObject)
}
extension Request {
public func responseObject<T: ResponseObjectSerializable>(completionHandler: Response<T, NSError> -> Void) -> Self {
let responseSerializer = ResponseSerializer<T, NSError> { request, response, data, error in
guard error == nil else { return .Failure(error!) }
let JSONResponseSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let result = JSONResponseSerializer.serializeResponse(request, response, data, error)
switch result {
case .Success(let value):
if let
response = response,
responseObject = T(response: response, representation: value)
{
return .Success(responseObject)
} else {
let failureReason = "JSON could not be serialized into response object: \(value)"
let error = Error.errorWithCode(.JSONSerializationFailed, failureReason: failureReason)
return .Failure(error)
}
case .Failure(let error):
return .Failure(error)
}
}
return response(responseSerializer: responseSerializer, completionHandler: completionHandler)
}
}
UIImage serializer for Alamofire, updated for Alamofire 2.0 and Swift 2
Alamofire 2.0 and Swift 2.0

Alamofire 'fatal error: unexpectedly found nil while unwrapping an Optional value'

When I am trying to server request in my swift code block, some errors occured after server response JSON like the code below;
Alamofire.request(.POST, Utility.WebServiceAddress+"/ApproveOrder", parameters: parameters)
.responseJSON
{(request, response, JSON, error) in
if let jsonResult: NSDictionary = JSON as? NSDictionary
{
if let wsResult = jsonResult[WSConstants.WSRESULT] as? NSDictionary
{
let resultCode = wsResult.valueForKey(WSConstants.RESULT_CODE) as Int
if(resultCode == Utility.WS_RESULT_SUCCESS)
{
self.PrepareMainItemsInBagToSetUpLocalNotifications()
Utility.ActivityIndicatorStopAnimating(self.activityIndicator, indicatorLabel: self.lblIndicatorMessage, viewController: self)
Utility.ReleaseBagAndPopToInitialViewController(self)
}
else
{
PromptDialogs.getPromptDialogWebServiceError(self.activityIndicator, lblIndicatorMessage: self.lblIndicatorMessage, viewController: self, message: "Sipariş tablebiniz gönderilirken hata oluştu. Lütfen tekrar deneyiniz!")
}
}
}
else
{
PromptDialogs.getPromptDialogWebServiceError(self.activityIndicator, lblIndicatorMessage: self.lblIndicatorMessage, viewController: self, message: "Sunucudan yanıt alınamadı. Lütfen internet bağlantınızı kontrol edip yeniden deneyiniz!")
}
} // gives 'fatal error: unexpectedly found nil while unwrapping an Optional value' at this line, as refering Alamofire code below ->
public func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
I used this request way for some other UIViewControllers. But I did not understand that why am I getting this error only here? If it is necessary for you, I can share the more detailed code block.
Could you help me ?
Best regards

Resources