unexpectedly found nil while unwrapping an Optional value - Using ALAMOFIRE - ios

I am trying to use Alamofire for GETs in JSON.
When I use one URL - It works fine and when I use another I get an error unwrapping an optional value. I cannot seem to track where the error is coming from. I have resorted in putting the code in ViewDidLoad to track the error. I don't know if its the recipient and they want some sort of authorisation. but I know its not the println's cos when i // them - it still comes up as an error , heres the code :
request(.GET, "https://api.doingdata.net/sms/send?api_service_key='APIKey'&msg_senderid=Edify-FYI&msg_to=&msg_text={otp|Edify-FYI|3600|ETEN|4} &msg_clientref=abcdef123456&msg_dr=0&output=json")
.validate()
.responseJSON { (_, _, _, error) in
println(error)
}
but I use :
request(.GET, "http://httpbin.org/")
.validate()
.responseJSON { (_, _, _, error) in
println(error)
}
it works fine and returns nil for the error.
Any help would be great, as its driving me nuts.

The reason is simple: your URL has special characters. So, if you do
let url = NSURL(string:yourURLString) //returns nil
It will return nil. You would need to format your URL to be suitable for making requests. Here is one solution for you.
var urlString = "https://api.doingdata.net/sms/send?api_service_key='APIKey'&msg_senderid=Edify-FYI&msg_to=&msg_text={otp|Edify-FYI|3600|ETEN|4} &msg_clientref=abcdef123456&msg_dr=0&output=json"
urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
request(.GET, urlString, parameters: nil, encoding: .JSON)

Related

Swift Alamofire - POST request using parameters of NULL value

I have the Alamofire POST request in the following and the value of my parameter is optional. I would like to allow users to call this API to set the required parameter, even though it is NULL (it's kind of reset to empty default value).
Here's my request and the parameter status is an optional variable that it's expected to be accepting null value:
let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
let parameters: [String : Any] = ["status": status as Any]
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
switch response.result {
case .success:
print("[Log] Update Status Success")
case .failure(let error):
print("[ERROR] UpdateStatus - \(error)")
APIErrorHandler(response: response, error: error)
}
}
However, I tried several times and it always returns some errors. I tried to be optional and I found that it isn't interpolated (i.e. it becomes "Optional(\"SOME_STATUS\")"). When I tried to force unwrap the string, those null values will cause fatal error. And also, I tried the methods of passing null as the value of the request parameter but it doesn't work anyway.
I don't understand how I should fix it, and could anyone help? Thanks a lot!
You can create the parameters dictionary then assign values to it.
In this case they key would either have a value of not exist.
var parameters: [String : Any] = [:]
parameters["status"] = status
Don't pass null parameter you can check it has value the pass it
check this code
let URL_UPDATE_STATUS = URL_HOME + "/v1/updateStatus/" + dataId
var parameters: [String : Any]? = nil
if let status = status {
parameters = ["status": status]
}
Alamofire.request(URL_UPDATE_STATUS, method: .post, parameters: parameters, encoding: URLEncoding(destination: .queryString), headers: self.headers).responseString { response in
switch response.result {
case .success:
print("[Log] Update Status Success")
case .failure(let error):
print("[ERROR] UpdateStatus - \(error)")
APIErrorHandler(response: response, error: error)
}
}
https://github.com/Alamofire/Alamofire/issues/2407
You just pass nil as the value and Alamofire does all the magic. The problem is most likely somewhere else.

How to send empty JSON via Alamofire?

How can i pass an empty JSON string to Alamofire and send POST request?
I tried like this:
let lazyPojo = LazyPojo()
let JSONString = Mapper<LazyPojo>().map(lazyPojo)
Alamofire.request(.POST, url, JSONString, encoding:.JSON).validate()
.responseJSON{...}
It says that my JSONString have to be Unwrapped, but when i run it i got this error: fatal error: unexpectedly found nil while unwrapping an Optional value.
How is this possible?
I think you didn't mention parameter name. So check this one :-
Alamofire.request(.POST, url, parameters: ["parameters": "\(JSONString)"])
.validate()
.responseJSON { }

My Router doesn't work after migration of Swift and update of Alamofire

I'm doing the migration of my app on Swift 2.0. I took the opportunity to also migrate Alamofire from 1.3 to 2.0.
But now my app is not working anymore, and i got many errors on the file where i use Alamofire.
First on my enum Router declaration i got an error who say
private enum Router: URLRequestConvertible {
EDIT: Here is the beginning of the methods that implement
URLRequestConvertible
// MARK: URLRequestConvertible
var URLRequest: NSURLRequest {
let URL = Router.baseURL.URLByAppendingPathComponent(self.path)
let URLRequest = NSMutableURLRequest(URL: URL)
URLRequest.HTTPMethod = self.method.rawValue
switch self {
case .Login(let email, let password):
return self.encoding.encode(URLRequest, parameters: [
"email": email,
"password": password]).0
case .Logout:
return self.encoding.encode(URLRequest, parameters: nil).0
}
Type 'Router' does not conform to protocol 'URLRequestConvertible'
Second in all my request when i'm gonna check the .responseJSON { (_, _, json, error) in i got an error who say
Tuple types '(NSURLRequest?, NSHTTPURLResponse?, Result)' (aka
'(Optional, Optional, Result)') and '(_, _, _, _)' have a different
number of elements (3 vs. 4)
EDIT: Ok no more error field but how do you do your error handling so ?
EDIT2: Ok got it now you need do use a switch for the Result. Thx
Error that i didn't had before
Thanks for your help !
For the second error refer to the Alamofire page here https://github.com/Alamofire/Alamofire
As you can see they changed the .responseJSON which now returns just 3 parameters. In version 1.3 there were 4 parameters instead. Basically you simply have to delete the error field in this way
.responseJSON { (_, _, json) in
I think you need to return 'NSMutableURLRequest' instead of 'NSURLRequest' if you havent changed that already.

Alamofire Get Request and JSON Response

I'm trying to use the Yoda API and send a request using the Alamofire Swift framework. I know that the API is correctly working, as I have tested the endpoint with my Mashape API key multiple times. I can also see that the requests are being sent (homepage of Mashape under my application). However my JSON response is always nil.
func handleRequest(words:String){
var saying = words.stringByReplacingOccurrencesOfString(" ", withString: "+");
saying = "?sentence=" + saying;
let url = NSURL(string: (baseURL+saying));
println(url);
var response:String;
Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = additionalHeaders;
Alamofire.request(.GET, url!).responseJSON { (_, _, JSON, _) in
println(JSON);
}
}
The words string can be "This is my first sentence" and it will automatically replace the spaces with "+" as per the API spec. Please Ignore the multiple println statements, they are just for debugging.
This is just proof of concept code, its purposely not doing much error checking and isn't pretty for that reason. If you have any suggestions I would appreciate them.
For some reason it's an issue I've too with the Alamofire request for JSON. It is the way I handle the JSON requests using Alamofire :
Alamofire.request(.GET, urlTo, parameters: nil, encoding: .URL).responseString(completionHandler: {
(request: NSURLRequest, response: NSHTTPURLResponse?, responseBody: String?, error: NSError?) -> Void in
// Convert the response to NSData to handle with SwiftyJSON
if let data = (responseBody as NSString).dataUsingEncoding(NSUTF8StringEncoding) {
let json = JSON(data: data)
println(json)
}
})
I strongly recommend you using SwiftyJSON to manage the JSON in a better and easy way, it's up to you.
I hope this help you.
Alamofire request have several method for handle response. Try to handle data response and convert it to String. Confirm that response JSON is normal.
Alamofire.request(.GET, url!).response { (_, _, data, error) in
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
println(str)
println(error)
}
Also checkout error while parsing JSON data.

iOS8/Swift strange null behaviour with response from REST service

Throughout my project I can perfectly check Alamofire responses and data for
if fooData != nil {
//do stuff
}
somehow in this instance Swift seems to have problems checking what the actual incoming type is
what I get if I print it is
<null>
what is this supposed to be? An array of null? Casts to NSDictionary or NSArray both fail.
The Rest response is the same as always throughout the project where I will potentially receive a null value and it gets catched everywhere else.
€dit with more code:
my request:
Alamofire.request(.GET, "\(CurrentConfiguration.serverURL)/api/users/\(CurrentConfiguration.currentUser.id)/friends/\(targetUser)",encoding:.JSON)
.validate()
.responseJSON {(request, response, friendData, error) in
if friendData != nil {
println(friendData!)
//this is where the app obviously crashes as there is nothing inside of "friendData"
let resp = friendData as NSDictionary
//load friendData into the UI
}
}
the print statement gives me the above mentioned null representation, but obviously does not recognize as nil
the response from the node backend comes as
index.sendJsonResponse(res, 200, null);
Try this code in Playground:
let fooData:AnyObject = NSNull()
println(fooData)
It prints <null>.
fooData is not nil, but a instance of NSNull

Resources