let theRequest = NSMutableURLRequest(URL: url!)
theRequest.HTTPMethod = "POST"
let parameters = ["otp":firstDigit.text!,"otp":secondDigit.text!,"otp":thirdDigit.text!,"otp":fourthDigit.text!] as Dictionary<String,String>
How to add parameters to pass numbers in to the server side. There is only one field in the server side and I have to pass 4 integers using four different text fields. How can I pass it? Basically I am passing an OTP(One time password with four digits)
First make the OTP variable like this:-
var otpText:String= firstDigit.text + secondDigit.text +thirdDigit.text+fourthDigit.text
then form the parameter:-
let parameters : NSDictionary =["otp":otpText]
Have you checked out the property HTTPBody: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableURLRequest_Class/#//apple_ref/occ/instp/NSMutableURLRequest/HTTPBody
Not compiled myself, but would be something like:
let otp = firstDigit.text + secondDigit.text+thirdDigit.text+fourthDigit.text
let json = [ "OTP" : otp ]
let jsonData = NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.allZeros, error: nil)
theRequest.HTTPBody = jsonData
What this code does:
Concatenate your text values to make a string
Create a dictionary (JSON object) with the key your server expected
and the value of the concatenated string
Convert that dictionary to NSData as expected by the HTTPBody property
Set the HTTPBody property on your NSMutableURLRequest
Also checkout out https://github.com/AFNetworking/AFNetworking. It makes it super simple to handle HTTP requests using iOS.
Related
I am making a call to an API where I want have status equal to final or in progress. Here is the call I am using:
let request = NSMutableURLRequest(url: NSURL(string: "https://sportspage-feeds.p.rapidapi.com/games?status=in%20progress||status=final")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
It works perfectly in Postman, but when trying it in my app it is crashing with this error:
Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
Is there a different way to use or in Swift?
You have manually percent encoded the space, but you have not percent encoded the two pipe characters. As a result the initialiser for NSURL fails, returning nil. Since you have force-unwrapped this value, your app then crashes.
You can use the function .addingPercentEncoding(withAllowedCharacters:) to percent encode a string appropriately and then create a URL.
Both percent encoding a string and creating a URL can fail, so these operations return an optional. You should use conditional unwrapping rather than force unwrapping to avoid crashes if these operations fail.
Many NS classes have bridged Swift equivalents including URLRequest for NSURLRequest and URL for NSURL. Idiomatic Swift eschews the use of an NS class when a Swift equivalent exists.
Use something like
if let urlStr = "https://sportspage-feeds.p.rapidapi.com/games?status=in progress||status=final".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(urlStr) {
let request = URLRequest(url, timeoutInterval: 10)
...
}
As Matt pointed out in a comment, the correct way to construct a URL in iOS is to use URLComponents. This allows you to specify each component of the URL independently and not worry about things like manual percent encoding.
The use of URLComponents is particularly important where you collect input from the user and they could attempt to manipulate the resulting URL string.
var components = URLComponents()
components.scheme = "https"
components.host = "sportspage-feeds.p.rapidapi.com"
components.path = "/games"
components.queryItems = [(URLQueryItem(name:"status", value:"in progress||status=final"))]
if let url = components.url {
let request = URLRequest(url, timeoutInterval: 10)
...
}
I'm trying to perform a HTTP request to a server: the content is a JSON object, which contains a numeric value for the key "amount". If the "amount" is a value with a decimal digit, e.g. 1.6, the request will contain the value
1.6000000000000001, and this value is not accepted by the Server (the api is Java made and the type is a float . I cannot send a String to the server, since the API that receives the data from me can only accept numbers for the "amount". I tried to perform the request with Siesta Framework or with dataTask, but the result is always the same
this is how I create the request (I omitted the less important parts)
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject) // jsonObject contains the Double value "amount"
let request = URLRequest(url: url)
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request)
task.resume()
Without code that fully reproduces the issue, it’s hard to say for sure, but I imagine what you’re seeing is this behavior:
let amount = 1.6 // Double
let jsonObject = ["amount": amount]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject)
String(data: jsonData, encoding: String.Encoding.utf8)
Swift Foundation’s JSON serialization always formats numeric values to their full precision — so the double-precision number 1.6 gets formatted as 1.6000000000000001.
Solution 1: Send a string
You can and should send a string if the server accepts it:
let amount = "1.6" // String
let jsonObject = ["amount": amount]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject)
String(data: jsonData, encoding: String.Encoding.utf8)
Note that a string is the only correct way to send this value if you are dealing with money or anything else where exact values matter: even if you spell it as 1.6, a standard JSON parser will likely convert it to a floating point on the receiving end.
Solution 2: Use Decimal to alter the formatting
If you just need to format it with less precision to make it pass validation on the server for some reason, you can embed it in the JSON as a Decimal instead of a Double and it will get formatted differently:
let amount = 1.6
let jsonObject = ["amount": Decimal(amount)]
let jsonData = try! JSONSerialization.data(withJSONObject: jsonObject)
String(data: jsonData, encoding: String.Encoding.utf8)
// {"amount":1.6}
You can even manipulate the Decimal to round to a certain precision.
Note, however, that this does not spare you from floating point precision issues: you are still sending a float according to the JSON spec, and it will still most likely be parsed as a float on the receiving end.
Without seeing your code it is challenging to offer help, however, one thing to check is whether you are using NumberFormatter to be sure you are getting the correct rounding on your values. Assuming you are pulling the number from a UITextField then you would need something like this:
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
if let textValue = textField.value {
var amount = numberFormatter.number(from: textValue)
}
I am building chat app and need to send and receive emoji images. I use following code to post data :
let myUrl = NSURL(string: "http://test.php")
let request = NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod = "POST"
let postString = " shareImageMessage=\(message)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
I can see my message with emojies in debug area as follows :
But only following image display in mysql database :
And following code from php script :
$shareImageMessage = $_POST["shareImageMessage"];
I couldn't understand why only one kind of image transferring.
To send more than one emoticon in the same url simply convert the string you are sending to the server to a base64 and then decode it on the other end of the database. To Encode and Decode strings to base64 you can check this Convert between UIImage and Base64 string. :)
SWIFT: encode the message with base64 like so:
func base64encode(message: NSString)->String{
let plainData = message.dataUsingEncoding(NSUTF8StringEncoding)
return plainData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.fromRaw(0))!
}
usage : let msgToPost = base64encode("born to be encoded 👻")
then in PHP just use the famous $decodedmsg = base64_decode($str);
this code worked perfectly for me
one more thing..
make sure that your database column supports emoji, you can refer to the question for more detail about fixing the database emoji thing
How to insert utf-8 mb4 character(emoji in ios5) in mysql?
I have JSONString from api as bellow:
[JSONString from api]
But after I read in iOS from Alamofire the order of the JSONString is not correct as api:
[JSON After read in iOS]
How can I keep the JSON format the same order as api?
As explained by #Nimit, JSON format represented in your callback and the API response is of least concern. What you need to care about is that when you are accessing the values from the response, the KEY should be same as seen in the API. No mismatch, not even of the case-sensitive letter, or you will always get the NIL in the response.
To explain it better to you with the use of Alamofire, let's me show you one example:
let APIURL = "https://api.yoururl.com"
Alamofire.request(.GET, APIURL , headers: headers) .responseJSON { response in
let value = response.result.value!
let JSONRes = JSON(value)
let KLValue = JSONRes["Kuala Lumpur"].int!
print(KLValue) //Or call a function to handle the callback
}
Here I am using SwiftyJSON for JSON. In the end, all you want to do is get the data out of the associated keys in the JSON response, no need to worry about how they have been formatted, or what's the order of Keys in the response - most of the time you will get the same as in the API - but in case it changes, need not to worry.
On the another front, to be sure that nothing happens to your app when JSON fields are nil, always put an if-let like this:
if let valueFromJSON = JSONRes["Kuala Lumpur"].string {
someVariable = valueFromJSON
} else {
someVariable = "No Value"
}
Thanks!
You can't do it, unless you write your own JSON parser. Any self-respecting JSON library won't guarantee you the order, if it wants to conform to the JSON spec.
From the definition of the JSON object:
the NSDictionary class represents an unordered collection of objects;
however, they associate each value with a key, which acts like a label
for the value. This is useful for modeling relationships between pairs
of objects.
If you have a jsonObject, such as data, then you can convert to json string like this:
let jsonString = JSONSerialization.data(withJSONObject: data,
options: JSONSerialization.WritingOptions.sortedKeys)
when you use sortedKeys option, the json will be specifies that the output sorts keys in lexicographic order.
I want to save data including string, number, date and coordinate in a file, and then transmit the file to a server. How to do this using swift?
And I'd like to process these data from the server in the future. What type of file is better to save them?
If i am getting this right you can use NSData
First you have to create a dictionary like this
var dictionary = [String:AnyObject]()
dictionary["age"] = 13
dictionary["name"] = "Mike"
Then you have to transform this dictionary into NSData using nsjsonserialization
if let data = NSJSONSerialization.dataWithJSONObject(dictionary, options:NSJSONWritingOptions(0), error:nil) as NSData? {
request.HTTPBody = data
}
But this is always depend on what the server is able to understand
Hope i helped. Sorry for my english