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
Related
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 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"
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
}
As I start to use Swift 3, I've got a problem with building a route with Google Maps API directions.
My route has several waypoints and in Swift 3 the URL:
https://maps.googleapis.com/maps/api/directions/json?origin=48.4843822562792,35.0635632500052&destination=48.4893899423081,35.0640017911792&waypoints=48.4833428800255,35.0710221379995|48.4887622031403,35.0573639944196&key=AIzaSyAWpBT3uxovKLqdWIiwa29a4AcgtspAA1k
Doesn't work because of "|". Any suggestions?
For those who wants to use directions googlemaps api, you have to send your waypoints in a parameters array. So the pipe doesn't cause problem anymore.
var wayPointsString = "optimize:true"
if waypointsForRequest.count > 0 {
for location in waypointsForRequest {
wayPointsString = "\(wayPointsString)|\(location.coordinate.latitude),\(location.coordinate.longitude)"
}
}
let parameters : [String : String] = ["key" : self.directionsApikey, "sensor" : "false", "mode" : "driving", "alternatives" : "true", "origin" : "\(origin.coordinate.latitude),\(origin.coordinate.longitude)", "destination" : "\(destination.coordinate.latitude),\(destination.coordinate.longitude)", "waypoints" : wayPointsString]
let url = URL(string: "https://maps.googleapis.com/maps/api/directions/json?")
Alamofire.request(url!, method:.get, parameters: parameters)
.validate(contentType: ["application/json"])
.responseJSON { response in
if response.value != nil {
let json = JSON(response.value!)
}
}
Interesting answer here : https://stackoverflow.com/a/40126476/3173405
Hi i didn't know much about swift., but i had the same problem in objective C and I did something below and worked for me,
NSMutableCharacterSet *alphaNumSymbols = [NSMutableCharacterSet characterSetWithCharactersInString:#"~!##$&*()-_+=[]:;',/?."];
[alphaNumSymbols formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:alphaNumSymbols];
NSURL *directionsURL = [NSURL URLWithString:urlString];
Hope this will help
in Swift,
var alphaNumSymbols = CharacterSet(charactersInString: "~!##$&*()-_+=[]:;',/?.")
alphaNumSymbols!.formUnion(CharacterSet.alphanumerics)
urlString = urlString.addingPercentEncoding(withAllowedCharacters: alphaNumSymbols)!
var directionsURL = NSURL(string: urlString)!
In Swift 3, the following helped
let url_string = "URL STRING"
let url = URL(string:url_string.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed))
Im trying to send a list of images from iOS application to a Django REST backend. This is the iOS Request using AlamoFire.
iOS Code:
let URL = "myURL"
var imagesDictonaryList = [[String : AnyObject]]()
var images = [UIImage]()
for _ in 1...3 {
images.append(UIImage(named: "profileImagePlaceholder")!)
}
//let imagesData = imagesToBase64(images)
for index in 0..<3 {
var myDictionary = [String:AnyObject]()
myDictionary["name"] = "\(index)"
myDictionary["image"] = images[index]
imagesDictonaryList.append(myDictionary)
}
print(imagesDictonaryList)
let parameters = [
"title": "service 1 title",
"description": "service 1 description",
"price": "11",
"images": imagesDictonaryList
]
Alamofire.request(.POST, URL, parameters: parameters as? [String : AnyObject]).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 dataString = String(data: response.data!, encoding: NSUTF8StringEncoding) {
print(dataString)
}
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Server Code:
views.py
class PredefinedServiceList(APIView):
"""
List all Predefined Services, or create a new Predefined Service
"""
permission_classes = (permissions.AllowAny,)
def post(self, request):
serializer = PredefinedServiceSerializer(data=request.POST)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
serializers.py
class ServiceImageSerializer(serializers.ModelSerializer):
def create(self, validated_data):
b64_text = validated_data.get('image', None)
image_data = b64decode(b64_text)
image_content = ContentFile(b"%s" % image_data, 'whatup.jpg')
validated_data['image'] = image_content
instance = ServiceImage.objects.create()
instance.save()
return instance
class Meta:
model = ServiceImage
fields = ('image', 'name')
class PredefinedServiceSerializer(serializers.ModelSerializer):
images = ServiceImageSerializer(many=True)
class Meta:
model = PredefinedService
fields = ('title', 'description', 'price', 'images')
def create(self, validated_data):
images_data = validated_data.pop('images')
service = PredefinedService.objects.create(**validated_data)
for image in images_data:
new_image, created = ServiceImage.objects.get_or_create(name=image.get('name', None))
new_image.image = image.get('image', None)
new_image.save()
service.images.add(new_image)
return service
models.py
class ServiceImage(models.Model):
image = models.ImageField(upload_to="predefined", null=True)
name = models.CharField(max_length=9001, null=True)
class PredefinedService(models.Model):
title = models.CharField(max_length=100, null=True, blank=True, default="untitled")
description = models.TextField(default="No description available.")
price = models.FloatField(default=0.000)
images = models.ForeignKey(ServiceImage, null=True, blank=True)
The problem is that the images are not in the request.data in the code but all other information sent are there.
the images are just an empty list after the iOS Client request. and the HTML i get is "index out of range" when hard coding list[0] to see the first picture received.
what might the problem be in this code? how to solve it? and is there any better way to implement this?
Files can be accessed via
request.FILES
so you would have to change
serializer = PredefinedServiceSerializer(data=request.POST)
to
serializer = PredefinedServiceSerializer(data=request.POST, files=request.FILES)
But if you're using DRF higher than 3.0, then according to the docs, the correct way to do this is using data attribute
serializer = PredefinedServiceSerializer(data=request.data)