post base64 string within url using Alamofire - ios

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.

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)

I received a response from the sever I wanted to decode it before I use it further

I have a string received from the server and I was trying to decode the string with padding but it is throwing nil as result. I tried codes that are available in stack overflow but of no use. Help will be highly appreciated.
I tried with base64 encoded with ignore unknown characters option and padding, still it throws nil.
let pem = "MIICyjCCAjOgAwIBAgIDBJPhMA0GCSqGSIb3DQEBBQUAMHsxEjAQBgNVBAMTCVJvb3RjZXJ0MTESMBAGA1UECRMJYmVsbGFuZHVyMQswCQYDVQQIEwJrYTEPMA0GA1UEERMGODg4ODg4MQwwCgYDVQQLEwNlc3MxGDAWBgNVBAoTD2VtdWRocmEgbGltaXRlZDELMAkGA1UEBhMCaW4wHhcNMTkwNzExMTAzNzM4WhcNMjgxMjI2MTAzNzM4WjB0MREwDwYDVQQDEwhBdmFkaGVzaDEMMAoGA1UECRMDYnRtMQswCQYDVQQIEwJrYTEPMA0GA1UEERMGODc4Nzg3MQwwCgYDVQQLEwNlc3MxGDAWBgNVBAoTD2VtdWRocmEgbGltaXRlZDELMAkGA1UEBhMCaW4wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMDAm7W3nc3hyyAhG8RBCSmlSDzcU/C39dPEFPq3N0JpSghMojnZg0jnfwXCvWqtPhlTYEdVLSXRehmQpS2v/FN8wkqZoVaKHNQE1UJnzPbyjfTlQA20nlCNVTNBQ70rWYzfuuFhliUBycGbYaIE/VGk354AEdXipLklCPf7PsgZAgMBAAGjYzBhMBIGA1UdEwEB/wQIMAYBAf8CAQAwHwYDVR0jBBgwFoAUkdq9ZIGVtD0x6k6hO7PdFMidh/QwHQYDVR0OBBYEFDwUkx0+5e1xTcavaVBpvREel/hZMAsGA1UdDwQEAwIBzjANBgkqhkiG9w0BAQUFAAOBgQBIDy2MjWWsZC9G1k3DFYyP2/jsj/xzKyQh2e5YrnxIGtK5jBRKZe3JOuq1wxMzRfzd22lnSyKzf4dKMp2ADXJnNQrB/aafGs9nf+FXuIomquZHoNGrThfSyB/tre8T3dMWRiUdYy74XL2wvQb6tVHPQ/UEPSYOyf3XDSnzpgtjmw=="
let decodedData = NSData(base64Encoded: dataStr, options: .ignoreUnknownCharacters)
let length = dataStr.count
dataStr = dataStr.padding(toLength: length + (4 - length % 4) % 4, withPad: "=", startingAt: 0)`
It has to give some decoded data with which I can create a certificate because the response is in the format of .cert.
A certificate is not a string. You cannot create a string from the raw Data.
You can decode the base64 encoded string simply with
let decodedData = Data(base64Encoded: dataStr)
Notes:
Don't use NSData in Swift.
The ignoreUnknownCharacters is not needed.
The padding is wrong. It's only required when encoding the data and the base64 related API of String and Data adds the = characters automatically.
May be It will Help
For Image I am doing like this
I am converting UIImage To data and Converting That data to base64EncodedString
let imageData = UIimage.pngData()
//encode string
let imgBase64Str = imageData?.base64EncodedString(options: .lineLength64Characters) ?? ""
//decoding string to data
let decodedData = Data(base64Encoded: imgBase64Str, options: .ignoreUnknownCharacters)

Alamofire post json and response json

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
}

Convert dictionary data into HTTP url format

i am trying to send dictionary data using POST method dataTaskWithRequest() can send this only in string URL format.
How can we convert dictionary data into HTTP URL format?
Here is an example:
let parameters = [
"first": "name",
"second": ["a", "b"],
"third": [
"x": 1,
"y": 2,
"z": 3
]
]
convert it into
first=name&second[]=a&second[]=b&third[x]=1&third[y]=2&third[z]=3
using swift 2.3
You can convert your dictionary to json using this code and set HTTPBody
let jsondata = NSJSONSerialization.dataWithJSONObject(parameters, options: .PrettyPrinted)
request.HTTPBody = jsondata
Faced the same issue. Converted the Dictionary using below code :
let postString = (dictionaryParameters.flatMap({ (key, value) -> String in
return "\(key)=\(value)"
}) as Array).joined(separator: "&")
and attached the string in httpBody of the request :
request.httpBody = postString.data(using: String.Encoding.utf8)
got the response finally.
Got help from this link:
Convert Swift Dictionary to String

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