Swift UTF8 encoding and non UTF8 character - swift

I've a some text from json file. In this text I've applied UTF8 encode but this encoder don't recognize a non standard character àèìòù and it's capital char, is there a method to purify my string?
My function:
func stringToUTF8String (stringaDaConvertire stringa: String) -> String {
let encodedData = stringa.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
//println(attributedString.string)
return attributedString.string
}

I've found a solution.
The UTF8 take 8 bit of table ASCII, and the UTF16 take 16 bit ASCII table, the solution is simple by modifying my function to:
func stringToUTF16String (stringaDaConvertire stringa: String) -> String {
let encodedData = stringa.dataUsingEncoding(NSUTF16StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
//println(attributedString.string)
return attributedString.string
}

Related

Swift 4: Type of expression is ambiguous without more context inside loop

I have a question:
I'm retrieving a long string made of some base 64 strings attached together with ";" separating each of them inside said string.
Here's my code:
if(item.photo != "null"){
let b64fullstring = item.photo
if(b64fullstring!.contains(";")){
let photos = b64fullstring!.split(separator: ";")
for pic in photos{
let base64encodedstring = pic
let decodedData = Data(base64Encoded: base64encodedstring!, options: Data.Base64DecodingOptions.ignoreUnknownCharacters)!
let decodedString = String(data: decodedData, encoding: .utf8)!
print(pic)
}
}
}
Its gives me the following error on the "data" function;
Type of expression is ambiguous without more context
I really don't get it.
When working on a single string, it works perfectly fine. But when using a loop, it gives this message for some reason.
Thank you for taking some of your time for helping me.
Swift errors are not very helpful. The problem there is that split method returns an array of substrings:
func split(separator: Character, maxSplits: Int = Int.max, omittingEmptySubsequences: Bool = true) -> [Substring]
And the Data initializer expects a String:
init?(base64Encoded base64String: String, options: Data.Base64DecodingOptions = [])
You just need to initialize a new string from your substring:
if let photos = b64fullstring?.split(separator: ";") {
for pic in photos {
if let decodedData = Data(base64Encoded: String(pic), options: .ignoreUnknownCharacters) {
if let decodedString = String(data: decodedData, encoding: .utf8) {
print(pic)
}
}
}
}
Another option is to use components(separatedBy:) method which returns an array of strings instead of substrings:
func components<T>(separatedBy separator: T) -> [String] where T : StringProtocol
if let photos = b64fullstring?.components(separatedBy: ";") {
for pic in photos {
if let decodedData = Data(base64Encoded: pic, options: .ignoreUnknownCharacters) {
if let decodedString = String(data: decodedData, encoding: .utf8) {
print(pic)
}
}
}
}

Incorrect format after parsing string HTML in Swift

While parsing I use this code
func encode() -> String{
var newStr = String(utf8String: self.cString(using: .utf8)!)
newStr = newStr!.removingPercentEncoding
guard let data = String(utf8String: self.cString(using: .utf8)!)?.data(using: .utf8) else {
return newStr!
}
guard let attributedString = try? NSAttributedString(data: data, options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html, NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
return newStr!
}
return attributedString.string
}
the problem is that it removes the \n.
So I do not display the text correctly
That's because you are using NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html
depending on what you are trying to accomplish, you may just ignore that fact or replace "\n" with something else in your String.

How to transfer HTML text into an attributed string without losing line breaks in Swift 3 [duplicate]

This question already has answers here:
HTML Format in UITextView
(8 answers)
Closed 5 years ago.
Please do not mark as duplicate. None of the existing questions solves not losing line breaks.
Given String: "Regular text becomes <b>bold with </b>\n\n<b><i>An italic</i></b>\n\n<b>Linebreak</b>"
I have two options:
let attrStr = try! NSAttributedString(
data: story.body.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSFontAttributeName: Handler.shared.setFont(FontNames.sourceSerifProRegular, 25.0)],
documentAttributes: nil)
This option loses the font, size and the line breaks.
The following extension from this answer, keeps UILabel's font, but it loses the line breaks as well.
extension UILabel {
func _slpGetSize() -> CGSize? {
return (text as NSString?)?.size(attributes: [NSFontAttributeName: font])
}
func setHTMLFromString(htmlText: String) {
let modifiedFont = NSString(format:"<span style=\"font-family: \(self.font!.fontName); font-size: \(self.font!.pointSize)\">%#</span>" as NSString, htmlText) as String
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
}
}
label.setHTMLFromString(htmlText: story.body)
What am I missing? What do I need to do to keep the line breaks?
Help is very appreciated.
Try set numberOfLines property in the UILabel.
For that, you can count the number of break lines and set into numberOfLines.
extension UILabel {
func _slpGetSize() -> CGSize? {
return (text as NSString?)?.size(attributes: [NSFontAttributeName: font])
}
func setHTMLFromString(htmlText: String) {
let modifiedFont = NSString(format:"<span style=\"font-family: \(self.font!.fontName); font-size: \(self.font!.pointSize)\">%#</span>" as NSString, htmlText) as String
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: .unicode, allowLossyConversion: true)!,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
self.numberOfLines = htmlText.components(separatedBy: "\n").count
}
}
I hope this example help you.

Trying to convert string looking like "ÐавлÑк ÐÑкÑоÑ" to correctly looking string

I've got a problem converting string looking like "ÐавлÑк ÐÑкÑоÑ" to correctly looking string.
I'm trying to use such way:
func stringToUTF16String (stringaDaConvertire stringa: String) -> String {
let encodedData = stringa.dataUsingEncoding(NSUTF16StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!
//println(attributedString.string)
return attributedString.string
}
But I got a compiler error: "Type of expression is ambisious withou more context" on that row:
let attributedString = NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil, error: nil)!

Extra 'data' argument in call

i have the following UILabel and i want to apply html text
var htmlText = "<b><i>sample text</i></b>"
var attrStr = NSAttributedString(
data: htmlText.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
label.attributedText = attrStr
the compiler send this Extra 'data' argument in call
any ideas?
I ran into a similar issue, except that I was supplying an empty dictionary for the options parameter.
if let string = NSAttributedString(data: data,
options: [],
documentAttributes: nil,
error: &error) {
self.textView.attributedText = string
}
When I switched it to nil instead, the compiler stopped complaining.
if let string = NSAttributedString(data: data,
options: nil,
documentAttributes: nil,
error: &error) {
self.textView.attributedText = string
}
You may need to case the options dictionary to [NSObject : AnyObject], since that is the type for that parameter.