Alamofire post json and response json - ios

i'm try to post a JSON using Swift3 and Alamofire and it work successfully in Postman Postman screen shot
but in code the response is HTML string that means an exception in server
i tried to change encoding from JsonEncoding.default to URLEncoding.default and it works good but after 3 days the same error when i run the app
let url = "http://mattam.net/mobileapp/addOrder"
let par:[String:Any] = ["order_restaurant":8,
"order_type":1,
"order_address":1,
"order_within":"45 mins",
"order_exacttime":"09:00 pm",
"order_total":300,
"order_fees":30,
"order_gtotal":330,
"order_user":38,
"pquantity[10]":3,
"pquantity[9]":1,
"poption[9]":238,
"pextra[10]":"80,81"]
print(par)
Alamofire.request(url, method: .post, parameters: par, encoding: URLEncoding.default).responseJSON{
r in
if r.result.isSuccess{print("------i______i-----")}
print(r)
if let result = r.result.value as? NSDictionary{
print(result)}
}
and in PostMan Bulk edit is
order_restaurant:8
order_type:1
order_address:1
order_within:45 mins
order_exacttime:09:00 pm
order_total:300
order_fees:30
order_gtotal:330
order_user:38
pquantity[10]:3
pquantity[9]:1
poption[9]:238
pextra[10]:80,81
and url is "let url = "http://mattam.net/mobileapp/addOrder""

Your problem is that your using http instead of https in your app.
The screenshot uses https while the url you posted (copied from your code) uses http.

If I understand your question right, you need to send some post details to the server as a Json, so here is some code to do that:
private func alamoFireAjax(url: String, parameters: Parameters, callback: #escaping (DataResponse<Any>) -> Void) {
Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON(completionHandler: callback)
}

I had a similar issue and to solve it I placed the dictionary creation in a method call. You can usually get away with most requests but I found anything larger than 10 rows needed a separate method handler.
fileprivate func generateParams() -> [String: Any] {
var params = [String: Any]()
params["order_restaurant"] = 8
params["order_type"] = 1
params["order_address"] = 1
params["order_within"] = "45 mins"
params["order_exacttime"] = "09:00 pm"
params["order_total"] = 300
params["order_fees"] = 30
params["order_gtotal"] = 330
params["order_user"] = 38
params["pquantity[10]"] = 3
params["pquantity[9]"] = 1
params["poption[9]"] = 238
params["pextra[10]"] = "80,81"
return params
}

Related

Array put request with Alamofire

I'm trying to make a put request with Alamofire and I want to pass in body something like this:
[
{
"id" : 1,
"position": 0
},
{
"id" : 2,
"position": 1
},
{
"id" : 6,
"position": 2
}
]
Normally, to do a request with alamofire I do this:
request = Alamofire
.request(
url,
method: method,
parameters: parameters,
encoding: encoding,
headers: buildHeaders());
Alamofire forces me to make parameters a dictionary but I want that paramaters to be an array of dictonary. How can I do this?
Thanks.
Alamofire added support for Encodable parameters in Alamofire 5, which provides support for Array parameters. Updating to that version will let you use Array parameters directly. This support should be automatic when passing Array parameters, you just need to make sure to use the version of request using encoder rather than encoding if you're customizing the encoding.
Well, the body of your parameters has type as [[String: Any]], or if you using Alamofire [Parameters].
So you if you parsing some Array of Objects to create this Array of parameters. You can do like this:
var positionedArray = [[String : Any]]()
for (index, item) in dataArray.enumerated() {
guard let id = item.id else {
return
}
let singleParameters : [String: Any] = ["id": id, "position" : index]
sorted.append(singleParameters)
}
As result, you can use this body (parameters), for your request.
Also, you should use JSONSerialization:
For example, if you using a customized Alamofire client, just use extension:
let data = try JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
let json = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
request.httpBody = json!.data(using: String.Encoding.utf8.rawValue)
var finalRequest = try URLEncoding.default.encode(request, with: nil)

Write to Google Sheets in Swift

I'm really confused how to write to an excel sheet, that is public. So far I have downloaded Alamofire and GoogleAPIClientForREST cocoapods. So I was wondering, if I want to write to the sheet do I first need to implement a google sign in or can I just send data over using Alamofire. I am super lost so If someone can help me that would be great.
Google sheet: https://docs.google.com/spreadsheets/d/1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0/edit#gid=0
func makeAndSendRequest() {
let baseUrl = "https://sheets.googleapis.com/v4/spreadsheets"
let spreadsheetId = "1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0"
let params = ["valueInputOption": "RAW"]
let range = "Studen!A3:B3"
//need to add params
let url = baseUrl + "/" + spreadsheetId + "/values/" + range + "/valueInputOption=RAW/"
let fullUrl = URL(string: url)!
//my values
let requestParams = [
"values": [
1,
2
]
]
//my auth is after Bearer so "Bearer 901390"
let header = ["Authorization":"Bearer "]
let requestURL = "https://sheets.googleapis.com/v4/spreadsheets/\(spreadsheetId)/values/\(range)?valueInputOption=RAW"
let req = Alamofire.request(requestURL, method: .put, parameters: requestParams, encoding: JSONEncoding.default,headers: header)
req.responseJSON { response in debugPrint(response) }
}
Try to fix this first.
valueInputOption is a query parameter, see: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update
You URL should at least be:
let url = baseUrl + "/" + spreadsheetId + "/values/" + range + "?valueInputOption=RAW"
next you need to fix your request body, range is required per document here: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/update
{
"range": "A3:B3",
"values": [
[
1,
2
]
]
}
This range should be same as your range in your query parameter, say Sheet1!:A3:B3 as in your query parameter.
Note that it starts with the sheet name, it should not be "studen"
I have used the playground tool on the same page and able to call the api to change the data in your spreadsheet.
At the end I am getting 200 response code and following json:
{
"spreadsheetId": "1zJR0uk6Pb6BuxJihFyxwe4ipQdBY4E9FFR74geBj8p0",
"updatedRange": "Sheet1!A3:B3",
"updatedRows": 1,
"updatedColumns": 2,
"updatedCells": 2
}
----- Edit -----
As you asked, the API needs Oauth token, the framework to handle this is actually called G Suite
Please find the guide here:
https://developers.google.com/gsuite/guides/ios

How to pass data in this format dictonary in array

I have tried many solution many times but any them not worked. finally if some one could help that would be really help. I will help you with the link and format of data need to be passed. You can check how postman to insert code and the below code which I tried. Thanks in advance!
This below way I insert data by postman :
insert : 0
Data : [{"user_id":"46","e_id":"566","date_list":"2018/04/25","t_depo":" 0.0","mini":"20","real_earn":"-5000.0","mb_balance":"-4000.0","balance_for":"4000"}]
The below code way I tried and I just get response updated successfully but no change in database when I check by postman
var dict = [String : String]()
dict["user_id"] = "46"
dict["e_id"] = "566"
dict["date_list"] = "2018/04/25"
dict["t_depo"] = " 0.0"
dict["mini"] = "200"
dict["real_earn"] = "-5000"
dict["mb_balance"] = "4000"
dict["balance_for"] = "4000"
var dictArray = [dict];
let parameter: Parameters = [
"insert" : "0",
"Data" : dictArray
]
Alamofire.request("url", method: .post, parameters: parameter, encoding: JSONEncoding.default)
.responseJSON {(response) in
print(parameter)
}
}
Seems that your "insert" is of type int and you're using a type string. Try with
let parameter: Parameters = [
"insert" : 0,
"Data" : dictArray
]
I would also check the response object. I believe you should get a status code 201 "Created"

post base64 string within url using Alamofire

I'm trying to post some images to server, which images are encoded in base64 string. i'm using Alamofire to post images and in my case, there are no parameter in my post method and all are in url.
here is how i encode images to base64 string:
let imageData:NSData = UIImagePNGRepresentation(data)! as NSData
let strBase64:String = imageData.base64EncodedString(options: .lineLength64Characters)
self.pictures[1] = strBase64
and here's my alamofire usage:
let header : HTTPHeaders = [
"Content-Type": "application/x-www-form-urlencoded"
]
url = "myUrl"
Alamofire.request(url.addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)! , method: .post, encoding: URLEncoding(destination: .methodDependent) , headers : header)
the service on server is FormUrlEncoded type. how can I send images, i'm using swift as my programming language.

Simple Post Request with Alamofire

It's my first post here, I'm trying to do this with Alamofire:
Swift code:
let name = "Taza"
let description = "50cl"
let parameters = ["name": name, "description": description]
Alamofire.request(.POST, "http://xxxxx.es/JSONpresenter.php?op=5", parameters: parameters, encoding: .JSON);
PHP code:
$op=$_GET['op'];
else if($op == 5)
{
// Get user id
$name = isset($_POST['name']) ? mysql_real_escape_string($_POST['name']) : “”;
$description = isset($_POST['description']) ? mysql_real_escape_string($_POST['description']) : “”;
add($name,$description);
}
But only get a register with "" in all cells. What am I doing wrong?
You need to use the URLEncoding instead of JSONEncoding for this particular case

Resources