How do I convert response.body from Vapor to String in Swift 3? - vapor

I'm using Vapor to try to get an XML file from another server, the problem is I don't know how to convert the response body to a swift String.
let bikesResponse = try drop.client.get("http://www.c-bike.com.tw/xml/stationlistopendata.aspx")
let bodyBytes = bikesResponse.body
let string = String(bytes) // <-- WHAT DO I DO HERE?
Thanks

Ah, ok I figured it out eventually.
let bikesResponse = try drop.client.get("http://www.c-bike.com.tw/xml/stationlistopendata.aspx")
if let bodyBytes = bikesResponse.body.bytes {
let string = String(bytes: bodyBytes, encoding: String.Encoding.utf8) {
}

Related

How to send Apostrophe ('s) in API request(Alamofire) swift 5?

I'm trying to send Apostrophe('s) in request using Alamofire.
I've tried below things but didn't get success
1) addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
2) addingPercentEncoding(withAllowedCharacters: .alphanumerics)
3) func utf8EncodedString()-> String {
let messageData = self.data(using: .nonLossyASCII)
let text = String(data: messageData!, encoding: .utf8) ?? ""
return text
}
After, searching relentlessly then finally I found one solution that we can turn off smart punctuation on particular textfield(smartQuotesType method).
try this:
let stringText = "This is my string"
let datas = ["myString": stringText]
guard let upload = try? JsonEncoder().encode(datas) else { return }
at this point send "upload" on your server, decode Json and use "myString" as variable for example in php:
$json = file_get_contents('php://input');
$array = json_decode($json, true);
$myString = $array["myString"];

Data is not converted into String

I am trying to convert an image into data and then that data into a string using this code but it fail on conversion when i want to convert data into string
let data = UIImagePNGRepresentation(selectedImageImageView.image!)
let datastring = String(data: data!, encoding: .utf8)
it gives some in data, but always nil in datastring
cant figure it out where the problem is if anyone knows please help... thanks
if let img = selectedImageImageView.image {
if let data = UIImagePNGRepresentation(img) {
if let datastring = data.base64EncodedStringWithOptions(.Encoding64CharacterLineLength) {
println(datastring)
}
}
}

Swift String escaping when serializing to JSON using Codable

I'm trying to serialize my object as following:
import Foundation
struct User: Codable {
let username: String
let profileURL: String
}
let user = User(username: "John", profileURL: "http://google.com")
let json = try? JSONEncoder().encode(user)
if let data = json, let str = String(data: data, encoding: .utf8) {
print(str)
}
However on macOS I'm getting the following:
{"profileURL":"http:\/\/google.com","username":"John"}
(note escaped '/' character).
While on Linux machines I'm getting:
{"username":"John","profileURL":"http://google.com"}
How can I make JSONEncoder return the unescaped?
I need the string in JSON to be strictly unescaped.
For iOS 13+ / macOS 10.15+
You can use .withoutEscapingSlashes option to json decoder to avoid escaping slashes
let user = User(username: "John", profileURL: "http://google.com")
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .withoutEscapingSlashes
let json = try? jsonEncoder.encode(user)
if let data = json, let str = String(data: data, encoding: .utf8) {
print(str)
}
Console O/P
{"profileURL":"http://google.com","username":"John"}
NOTE: As mention by Martin R in comments \/ is a valid JSON escape sequence.
I ended up using replacingOccurrences(of:with:), which may not be the best solution, but it resolves the issue:
import Foundation
struct User: Codable {
let username: String
let profileURL: String
}
let user = User(username: "John", profileURL: "http://google.com")
let json = try? JSONEncoder().encode(user)
if let data = json, let str = String(data: data, encoding: .utf8)?.replacingOccurrences(of: "\\/", with: "/") {
print(str)
dump(str)
}
I got it. The thing was that it didn't contain any \ character. It is just the property of swift that it will always return such a string on a console. The workaround is to j-son parse it.
Still, you can be used below solution of replacing '\/' with "/" string
let newString = str.replacingOccurrences(of: "\\/", with: "/")
print(newString)
While playing around JSONEncoder/JSONDecoder,
I found that the URL type is lossy on encode -> decode.
Initializes with a string, relative to another URL.
init?(string: String, relativeTo: URL?)
Might be help this apple document: https://developer.apple.com/documentation/foundation/url
using the PropertyList version, however:
let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = PropertyListDecoder().decode([URL].self, from: PropertyListEncoder().encode([User]))
Other way
let url = URL(string: "../", relativeTo: URL(string: "http://google.com"))!
let url2 = JSONDecoder().decode([URL].self, from: JSONEncoder().encode([User]))
Hope will helpful to you!!
Actually you cannot do that since in macOS and Linux are a bit different escaping systems. On linux // is allowed, macOS - not(it uses NSSerialization). So, you can just add percent encoding on your string, which guarantees you equal strings on macOS and linux, right string posting to a server and right validating. On adding percent escaping set CharacterSet.urlHostAllowed. Could be done like this:
init(name: String, profile: String){
username = name
if let percentedString = profile.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlHostAllowed){
profileURL = percentedString
}else{
profileURL = ""
}
}
In the same manner, you can removePercentEncoding
AND YOU DONT NEED MODIFY SERVER SIDE!!!

use emoji in label from ios default keyboard

i want to use text input and emoji from iOS default keyboard and send it to server and show that text to label but i am not able to display emojis.it only display text but not emojis.
if i do it locally than it will display emoji.
self.labelName.text = TextFiled.text
output : "test 😘😝"
but when i send send it to server and receive from it from api than emoji is gone.
output : "test"
please dont down vote my question without any reason
Swift 3.0 Extension solution:
You need to encode and decode emoji's on iOS side when sending it to server. You can do it as below.
extension String {
func encodeChatString() -> String? {
if let encodedTextData = self.data(using: .nonLossyASCII) {
return String(data: encodedTextData, encoding: .utf8)
}
return nil
}
func decodeChatString() -> String? {
let trimmedString = self.trimmingCharacters(in: .whitespacesAndNewlines)
if let stringData = trimmedString.data(using: .utf8) {
let messageString = String(data: stringData, encoding: .nonLossyASCII)
return messageString
}
return nil
}
}
When you send message encode string like below:
message.encodeChatString()
When you receive message decode string like below:
message.decodeChatString()
When send a data to server use this method .
let data1 = txtMessage.text.dataUsingEncoding(NSNonLossyASCIIStringEncoding)!
let finalmessage = String(data: data1, encoding: NSUTF8StringEncoding)
when you get a response from server before set in label use this method.
let trimmedString = YOURSERVER_RESPONSE_STRING.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet())
let data2 = trimmedString.dataUsingEncoding(NSUTF8StringEncoding)!
let messagestring = String(data: data2, encoding: NSNonLossyASCIIStringEncoding)
YOURLABEL.text = messagestring as String
Try this your problem solve.

How to convert string to unicode(UTF-8) string in Swift?

How to convert string to unicode(UTF-8) string in Swift?
In Objective I could write smth like that:
NSString *str = [[NSString alloc] initWithUTF8String:[strToDecode cStringUsingEncoding:NSUTF8StringEncoding]];
how to do smth similar in Swift?
Swift 4 and 5 I have created a String extension
extension String {
func utf8DecodedString()-> String {
let data = self.data(using: .utf8)
let message = String(data: data!, encoding: .nonLossyASCII) ?? ""
return message
}
func utf8EncodedString()-> String {
let messageData = self.data(using: .nonLossyASCII)
let text = String(data: messageData!, encoding: .utf8) ?? ""
return text
}
}
Swift 4:
let str = String(describing: strToDecode.cString(using: String.Encoding.utf8))
Use this code,
let str = String(UTF8String: strToDecode.cStringUsingEncoding(NSUTF8StringEncoding))
hope its helpful

Resources