Skip to content

Instantly share code, notes, and snippets.

@abbeyjackson
Last active December 18, 2015 16:37
Show Gist options
  • Save abbeyjackson/1480de64749543615547 to your computer and use it in GitHub Desktop.
Save abbeyjackson/1480de64749543615547 to your computer and use it in GitHub Desktop.
NSAttributed String from an HTML JSON response. Rather than putting it in a web view with dynamic height, can convert to an attributed string with formatting.
func getJSONData() -> NSData? {
guard let path = NSBundle.mainBundle().pathForResource("staticText", ofType: "json") else {
print("error finding file")
return nil
}
return NSData(contentsOfFile: path)
}
func dataToJSON(data:NSData) -> [String: AnyObject]? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String: AnyObject]
} catch let error {
DDLogSwift.error("error: \(error)")
return nil
}
}
func formatHomeScreenTagline() {
if let jsonFileData = getJSONData(),
let json = dataToJSON(jsonFileData),
let text = json["text"] as? [String: AnyObject],
let homeTextLabelString = text["homeTextLabel"] as? String,
let data = homeTextLabelString.dataUsingEncoding(NSUTF8StringEncoding) {
do {
let attributedString = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
homeTextLabel.attributedText = attributedString
}
catch let error {
DDLogSwift.info("Tagline was not loaded, error: \(error)")
}
}
}
{
"text": {
"homeTextLabel": "<html><head><style type=\"text/css\"> *{font-family: Lato-Regular;font-size: 24pt;} .highlighted{color: #87ab3f;} .strikethrough{text-decoration: line-through} </style></head><body>We use <span class=\"highlighted\">technology</span> to build grow & change <span class=\"strikethrough\"><span class=\"regularText\">companies</span></span> <span class=\"highlighted\">lives</span>.</body></html>"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment