How to send empty JSON via Alamofire? - ios

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 { }

Related

Alamofire post request error Extra argument 'method' in call

I'm using xcode 9.2 I want to make a post request however I'm getting this error "Extra argument 'method' in call". I know it's talking about the post method but i dont know how to fix it, can anyone help?
Alamofire.request(URL_REGISTER, method: .post, parameters: body, encoding: JSONEncoding, headers: header).responseString {
(response) in
if response.results.error == nil {
completion(true)
} else {
completion(false)
debugPrint(response.resultd.error as Any)
}
}
your attributes probably aren't valid (if the types don't match Xcode will tell you the error with the closest matching function)
try changing JSONEncoding to JSONEncoding.default and that your body matches [String:Any]
Alamofire.request(String, method: HTTPMethod.post, parameters: [String:Any], encoding: JSONEncoding.default, headers: header)
something along these lines (I don't know about the header attribute I usually have this at nil)
It probably is because your body variable isn't [String: Any]

How to pass JSON object in Alamofire request swift 3

I am doing service calls using Alamofire API. So far GET methods are working fine. And now I need to do a PUT request. Also it is accepting body parameters in this type.
{
"LeaveEntryCode":0,
"RequestId":0,
"EmployeeCode":17227,
"LeaveYear":2017,
"LeaveTypeCode":1,
"LeaveReasonCode":1,
"BaseType":"ess",
"StartDate":"2017-06-16T00:00:00",
"EndDate":"2017-06-16T00:00:00",
"NoOfDays":1.0,
"StartDateSession":"full",
"EndDateSession":"full",
"PreApproved":false,"ForDate":"1901-01-01T00:00:00",
"Remarks":"I have to attend for a wedding of my close relatives",
"CoveringPersonCode":0,
"RequestStatus":"P",
"Deleted":false,
"Status":false,
"CreatedBy":0,
"CreatedDate":"0001-01-01T00:00:00",
"UpdatedBy":0,
"UpdatedDate":"0001-01-01T00:00:00",
"DeletedBy":0,
"DeletedDate":"0001-01-01T00:00:00",
"ModuleId":2,
"ObjectId":20,
"StartDateString":"06/16/2017",
"EndDateString":"06/16/2017",
"LeaveDayList":["06/16/2017-FH,06/16/2017-SH"],
"SystemLeaveTypeCode":"ANN",
"LeaveTypeName":"ANNUAL",
"Employee":null,
"LieuDayList":null,
"BaseLeaveType":"ANN",
"CoveringPersonName":"",
"LeaveReasonName":"Personal",
"DocumentSource":"LEAVE",
"AttachedDocument":null
}
I created a [String:Any] object and assigned to parameters in the following request.
But I got an error called Extra argument 'method' in the call.
But If I assigned it as ["":""] that error disappears. How can I solve this? Please help me.
Alamofire.request(urlString, method: method, parameters: parameters, encoding: JSONEncoding.default, headers: headerToken)
UPDATE
var dictionary:[String:String]!
dictionary=[
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]
You got an error called Extra argument 'method' in call which is due to headers,
Try passing headers as nil or as follows :
//Here param equals to your dictionary as [String :Any]
//Pass Headers as Dictionary as well.
Alamofire.request("", method: .post, parameters: param, encoding: JSONEncoding.default, headers:["" : ""])
It Worked for me.
Check this link as well:
Alamofire Swift 3.0 Extra parameter in call
//try this
Alamofire.request(urlString, method: method, parameters: parameters as! Parameters, encoding: JSONEncoding.default, headers: headerToken)
parameters should be of Parameters type not dictionary.
try this:
let parameters: Parameters = [
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]
Make the parameters of type [String:AnyObject]? and depending on whether you need parameters or not assign value to it or set it as nil. For headers make it of type [String:AnyObject]?. So if you don't have header make it nil. For example
var dictionary:[String:String]?
if shouldAddParams{
dictionary=[
"LeaveEntryCode":"0",
"RequestId":dm.strReqID,
"EmployeeCode":dm.strEmpCode,
"LeaveYear":dm.selectedYear,
"LeaveTypeCode":dm.selectedLeaveTypeCode,
"BaseType":"ess",
"StartDate":dm.startDate,
"EndDate":dm.endDate,
"NoOfDays":dm.noOFDays,
"StartDateSession":dm.startDateSession,
"EndDateSession":dm.endDateSession,
"RequestStatus":"P",
"PreApproved":"0",
"ForDate":"01/01/1901",
"Remarks":comment,
"CoveringPersonCode":dm.strcoveringPersonCode,
"LeaveDayList":strDayLvList,
"BaseLeaveType":dm.selectedLeaveTypeCode,
"LeaveReasonCode":dm.selectedReasontypeCode,
"AttachedDocument":"null"
]
} else {
dictionary = nil
}

Unable to parse JSON response object Alamofire

I am making a post request and get back a JSON response in the form of [Object object]. I tried various ways to parse this JSON but wasn't able to. Whenever I try, I get an error saying Could not cast value of type '__NSCFString' (0x10f3dc4a0) to 'NSData'
On the backend side, I have a NodeJS server that replies with res.send. Do I need to convert this data to something else or is there a way I can parse this JSON Data and get the Dictionary object that I am originally supposed to get. I'm using Swift 3 with Alamofire 4.0.
How can I solve this issue?
This is my request code in iOS
Alamofire.request(urlString, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
debugPrint(response)
let data_temp = try! JSONSerialization.jsonObject(with: response.result.value! as! Data, options: JSONSerialization.ReadingOptions.mutableContainers)
print(data_temp)
}
}

IOS Swift Alamofire JSON Request

I am trying to make a JSON Request with Alamofire but the response is in Greek and Swift returns:
Response
{
id = 4;
name = "\U0395\U03bb\U03b1\U03b9\U03cc\U03bb\U03b1\U03b4\U03bf"
url = "http://www.gaiaskarpos.com/app/images/categories/olive.png";
}
The problem is at name field.
//Swift Alamofire Request
Alamofire.request(.GET, "http://gaiaskarpos.com/applegetCategores.php",
encoding:.JSON).validate().responseJSON{(response)->
Void in print("Response Json : \(response.result.value)")
I had a same issue in Arabic/Persian chars and It's my solution:
json variable :
{
message = "\U062f\U0633\U062a\U06af\U0627\U0647 \U0645\U0639\U062a\U0628\U0631 \U0646\U06cc\U0633\U062a";
status = 0;
}
So I casted json to [String: AnyObject] :
var test = json as? [String : AnyObject]
print(test)
It's fixed. You should give it a try.
Why is your encoding .JSON? You send .GET-request and you don't need to specify the type of encoding in your request.
Alamofire documentation say:
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
.responseJSON { response in
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
So use it. Links -> http://cocoadocs.org/docsets/Alamofire/1.1.3/ and https://github.com/Alamofire/Alamofire
You must specify the type of encoding when you pass parameters in the body of your request. It is for .POST and .PUT requests.
Try to print 'name' to Debug area. Maybe you'll get name in normal encoding... Xcode has the disadvantage: it shows not-UTF8 data in response like '\U0395\U03bb ... ... ... \U03b1\U03b9\' when there is some level of nested data in response.
Try to use NSUTF8StringEncoding with alamofire response
encoding: NSUTF8StringEncoding
Try to serialize the JSON with below code this might help you
let dict = NSJSONSerialization.JSONObjectWithData(jsonString.dataUsingEncoding(NSUTF8StringEncoding)!,
options: nil, error: nil) as [String : String]

unexpectedly found nil while unwrapping an Optional value - Using ALAMOFIRE

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)

Resources