How to convert string to unicode(UTF-8) string 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
}
}
How convert string to utf-8? (Swift, Alamofire)
Swift 3
let newStr = String(utf8String: stringToDecode.cString(using: .utf8)!)
Source StackOverFlow
Can the conversion of a String to Data with UTF-8 encoding ever fail?
UTF-8 can represent all valid Unicode code points, therefore a conversion
of a Swift string to UTF-8 data cannot fail.
The forced unwrap in
let string = "some string .."
let data = string.data(using: .utf8)!
is safe.
The same would be true for .utf16
or .utf32
, but not for
encodings which represent only a restricted character set,
such as .ascii
or .isoLatin1
.
You can alternatively use the .utf8
view of a string to create UTF-8 data,
avoiding the forced unwrap:
let string = "some string .."
let data = Data(string.utf8)
Decode string using UTF-8 in swift 5
This is the output you get if at some point UTF-8 data was interpreted as Latin1. For example:
let s = "Kawran Bazar FDC Road, East Nakhalpara, নিকেতন, ঢাকা, ঢাকা বিভাগ, বাংলাদেশ"
let utf8Data = Data(s.utf8)
let latin1 = String(data: utf8Data, encoding: .isoLatin1)!
print(latin1)
==>
Kawran Bazar FDC Road, East Nakhalpara, নিà¦à§à¦¤à¦¨, ঢাà¦à¦¾, ঢাà¦à¦¾ বিà¦à¦¾à¦, বাà¦à¦²à¦¾à¦¦à§à¦¶
You should first try to fix this and remove this incorrect string creation. If you cannot, then you can round-trip it back through Latin1.
let latin1Data = latin1.data(using: .isoLatin1)!
let utf8String = String(data: latin1Data, encoding: .utf8)!
utf8String == s // true
Convert String to Data base HTTP.UTF8 in swift
Your question is difficult to understand as you don't explain what "ExpDate":"ZIT5KR2+4Mk="
is. In which part is it contained? I assume ExpDate is a property param dictionary that's serialized into JSON. I further assume that the plus character is the original character after the Base64 encoding and wasn't inserted when the URL request was built.
Your server obviously expects a POST request with URL encoded form data. This kind of request is natively supported by Android (UrlEncodedFormEntity
) but not by iOS. To achieve the same, you cannot just concatenate the key/value pairs. You must properly URL encode them as well.
To that end, I propose the following URLRequest
extension:
import Foundation
extension URLRequest {
private static let alloweCharacters = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 -_.*")
public mutating func setURLEncodedFormData(parameters: [String: String?]) {
var encodedParameters = ""
for (key, value) in parameters {
if !encodedParameters.isEmpty {
encodedParameters += "&"
}
encodedParameters += URLRequest.urlEncoded(value: key)
encodedParameters += "="
if let value = value {
encodedParameters += URLRequest.urlEncoded(value: value)
}
}
self.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
self.httpBody = encodedParameters.data(using: .utf8)
}
private static func urlEncoded(value: String) -> String {
return value.addingPercentEncoding(withAllowedCharacters: alloweCharacters)!.replacingOccurrences(of: " ", with: "+")
}
}
It can be used like this (tested in Playground):
var request = URLRequest(url: URL(string: "http://somehost.com/someservice")!)
request.httpMethod = "POST"
let jsonString = "{ \"ExpDate\" : \"ZIT5KR2+4Mk=\", \"SomeString\" : \"%=&\" }"
var params = [ "action": "payment", "key": "hmn@$Q&*$GD4@!$#", "input": jsonString]
request.setURLEncodedFormData(parameters: params)
I hope it solves your problem.
Related Topics
Swift Error: Editor Placeholder in Source File
Firebase Dynamic Link Always Goes to App Store Url Even If the App Is Installed
Array of Multiple Url's Nsfilemanager Swift
Why Isn't Preferredcontentsize Used by iPhone 6 Plus Landscape
Firebase - How to Get the Key Value in Observeeventtype = Value
Convert Nsattributedstring into Data for Storage
Swipe Left or Right to Load the View Controller with the Collection View Cell Highlight
How to Automatically Convert Manual Retain-Release Code to Arc
Using iOS 6 Theme for iOS 7 App
Uisearchbar's Cancel and Clear Buttons Not Working in iOS 7
How to Select a Picker View Item in an iOS UI Test in Xcode
Static VS Class as Class Variable/Method (Swift)
Xcode Error:Distill Failed for Unknown Reasons
Where Does a Swift iOS Application Begin Its Life
Avaudiosession .Defaulttospeaker Changes Mic Input