How to display HTML text(as string) on UILabel with hyperlinks? - html

I want to display a string(which is actually a small HTML code, with hyperlink) on UILabel. E.g. The string which I have to display is: "Click here to know more". So is there a way to display it on UILabel, and on clicking the hyperlink(Click here) it opens up the desired web page?
Here's what I did:
#IBOutlet weak var testLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let htmlData = NSString(string: "Click here to know more").data(using: String.Encoding.unicode.rawValue)
let attributedString = try? NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
testLabel.attributedText = attributedString
}
The label displayed the string just like I wanted, but on clicking the hyperlink, it didn't do what what desired, i.e. open a web page.

Try to use UITextView instead of UILabel
#IBOutlet weak var testTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
testTextView.isEditable = false
testTextView.dataDetectorTypes = .link
testTextView.isScrollEnabled = false
let htmlData = NSString(string: "Click here to know more").data(using: String.Encoding.unicode.rawValue)
let attributedString = try? NSAttributedString(data: htmlData!, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil)
testTextView.attributedText = attributedString
}

#IBOutlet weak var testLabel: UILabel!
let message = "Please <a href='https://www.google.com'>click here</a> to search"
#override func viewDidLoad() {
super.viewDidLoad()
formatLabel(with: message.htmlToString)
}
func formatLabel(with message: String) {
let formattedText = String.format(strings: ["click here"],
boldFont: UIFont.init(name: "Roboto-Bold", size: 16.0)!,
boldColor: UIColor.blue,
inString: message,
font: UIFont.init(name: "Roboto-Regular", size: 16.0)!,
color: UIColor(red: 33/255, green: 136/255, blue: 189/255, alpha: 1.0))
testLabel.attributedText = formattedText
testLabel.numberOfLines = 0
let tap = UITapGestureRecognizer(target: self, action: #selector(handleTermTapped))
testLabel.addGestureRecognizer(tap)
testLabel.isUserInteractionEnabled = true
testLabel.textAlignment = .center
}
#objc func handleTermTapped(gesture: UITapGestureRecognizer) {
let clickString = (testLabel.text ?? "") as NSString
let clickRange = clickString.range(of: "click here")
let tapLocation = gesture.location(in: testLabel)
let index = testLabel.indexOfAttributedTextCharacterAtPoint(point: tapLocation)
if checkRange(clickRange, contain: index) == true {
guard let url = URL(string: "https://www.google.com") else { return }
UIApplication.shared.open(url, options: [:], completionHandler: nil)
return
}
}
Helper function and extensions:
func checkRange(_ range: NSRange, contain index: Int) -> Bool {
return index > range.location && index < range.location + range.length
}
extension String {
static func format(strings: [String],
boldFont: UIFont = UIFont.init(name: "Roboto-Bold", size: 16.0)!,
boldColor: UIColor = UIColor.blue,
inString string: String,
font: UIFont = UIFont.init(name: "Roboto-Regular", size: 16.0)!,
color: UIColor = UIColor(red: 33/255, green: 136/255, blue: 189/255, alpha: 1.0)) -> NSAttributedString {
let attributedString =
NSMutableAttributedString(string: string,
attributes: [
NSAttributedString.Key.font: font,
NSAttributedString.Key.foregroundColor: color])
let boldFontAttribute = [NSAttributedString.Key.font: boldFont, NSAttributedString.Key.foregroundColor: boldColor]
for bold in strings {
attributedString.addAttributes(boldFontAttribute, range: (string as NSString).range(of: bold))
}
return attributedString
}
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
extension UILabel {
func indexOfAttributedTextCharacterAtPoint(point: CGPoint) -> Int {
let textStorage = NSTextStorage(attributedString: self.attributedText!)
let layoutManager = NSLayoutManager()
textStorage.addLayoutManager(layoutManager)
let textContainer = NSTextContainer(size: self.frame.size)
textContainer.lineFragmentPadding = 0
textContainer.maximumNumberOfLines = self.numberOfLines
textContainer.lineBreakMode = self.lineBreakMode
layoutManager.addTextContainer(textContainer)
let index = layoutManager.characterIndex(for: point, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil)
return index
}
}

Here is simple demo of how to do what you need with UILabel
import UIKit
class ViewController : UIViewController {
override func loadView() {
let view = UIView()
view.backgroundColor = .white
let label = UILabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.attributedText = NSAttributedString(string: "Tap Me", attributes: [.link : URL(string: "http://www.google.com")!])
label.isUserInteractionEnabled = true
label.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleLink(_:))))
view.addSubview(label)
self.view = view
}
#IBAction func handleLink(_ sender: UIGestureRecognizer) {
guard sender.state == .ended else { return }
guard let label = sender.view as? UILabel else { return }
guard let link = label.attributedText?.attribute(.link, at: 0, effectiveRange: nil) as? URL else { return }
UIApplication.shared.open(link, options: [:], completionHandler: nil)
}
}

Related

how to create mapkit annotations by using data json data from server?

I read from my server and print it out in my xcode project. But when I tried to represent the json code to show mapkit annotations according to latitude and longitude from the server it would not work.
Here is my structure:
struct User {
var locaitonid: String
var latitude: Double
var longitude: Double
var cityName: String
init(_ dictionary: [String: Any]) {
self.locaitonid = dictionary["location_id"] as? String ?? ""
self.latitude = dictionary["latitude"] as? Double ?? 0.0
self.longitude = dictionary["longitude"] as? Double ?? 0.0
self.cityName = dictionary["city_name"] as? String ?? ""
}
Here is my viewController code:
class ViewController: UIViewController {
var model = [User]()
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://web server link ") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
for dic in jsonArray{
let annotation = MKPointAnnotation()
annotation.title = (dic["location_id"] as! String)
annotation.subtitle = (dic["city_name"]as! String)
annotation.coordinate = CLLocationCoordinate2D(latitude: dic["latitude"]as!Double, longitude: dic["longitude"]as!Double)
self.mapView.addAnnotations([annotation])
self.mapView.showAnnotations([annotation], animated: true)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
Try the following code
class ViewController: UIViewController {
var model = [User]()
#IBOutlet weak var mapView: MKMapView!
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://web server link ") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
// print(jsonResponse) //Response result
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
for dic in jsonArray{
let annotation = MKPointAnnotation()
annotation.title = (dic["location_id"] as! String)
annotation.subtitle = (dic["city_name"]as! String)
annotation.coordinate = CLLocationCoordinate2D(latitude: dic["latitude"]as!Double, longitude: dic["longitude"]as!Double)
DispatchQueue.main.async {
self.mapView.addAnnotations([annotation])
self.mapView.showAnnotations([annotation], animated: true)
}
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}

Home viewcontroller is not responding after sign in to the app in swift

For designing i am using storyboards. Home view controller contains side menu in separate view and i have designed home with collection view. for side menu i am using ENSideMenu which contains MyNavigationController.. if i give MyNavigationController as a is initial view controller then home is working fine but when i give sign in view controller as a is initial view controller then home view controller appears but collection view and side menu is not responding while tapping.
Here is my code:
In appdelegagte:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let userId: String? = KeychainWrapper.standard.string(forKey: "Uid")
print("appdelegate userid \(userId)")
if userId != nil{
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeVC = mainStoryBoard.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
self.window!.rootViewController = homeVC
}
return true
}
in signin vc:
func logInService(){
let parameters = ["username":Int(userIdTextFielf.text ?? ""),
"password":passwordTextField.text] as? [String : Any]
let url = URL(string: "https://dev.anyemi.com/webservices/anyemi/login")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters as Any, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if let response = response {
// print(response)
}
if let data = data {
do{
let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("the json of loginnnnnn \(json)")
let Uid = json["id"] as? String
let loginPhoneNum = json["user_id"] as? String
let nameL = json["user_name"] as? String
let emailL = json["user_email"] as? String
let saveUserId: Bool = KeychainWrapper.standard.set(Uid!, forKey: "Uid")
print("the userid is \(saveUserId)")
if (Uid?.isEmpty)!
{
print("login fail")
}
else{
DispatchQueue.main.async {
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let appDelagate = UIApplication.shared.delegate
appDelagate?.window??.rootViewController = homeVC
}
}
}catch{
print("error")
}
}
}).resume()
}
in home vc:
import UIKit
struct JsonData {
var iconHome: String?
var typeName: String?
init(icon: String, tpe: String) {
self.iconHome = icon
self.typeName = tpe
}
}
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
#IBOutlet weak var collectionView: UICollectionView!
var itemsArray = [JsonData]()
override func viewDidLoad() {
super.viewDidLoad()
homeServiceCall()
//Do any additional setup after loading the view.
collectionView.delegate = self
collectionView.dataSource = self
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsets(top: 2.0, left: 2.0, bottom: 2.0, right: 2.0)
layout.itemSize = CGSize(width: 95, height: 95)
collectionView?.collectionViewLayout = layout
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Hide the navigation bar on the this view controller
self.navigationController?.setNavigationBarHidden(true, animated: true)
}
#IBAction func sideMenuButton(_ sender: Any) {
print("in side menu")
toggleSideMenuView()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return itemsArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HomeCollectionViewCell
let aData = itemsArray[indexPath.row]
cell.paymentLabel.text = aData.typeName
if let url = NSURL(string: aData.iconHome ?? "") {
if let data = NSData(contentsOf: url as URL) {
cell.paymentImage.image = UIImage(data: data as Data)
}
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let nextViewController = self.storyboard?.instantiateViewController(withIdentifier: "MakePaymentViewController") as! MakePaymentViewController
self.navigationController?.pushViewController(nextViewController, animated: true)
let indexPath = indexPath.row
}
//MARK:- Service-call
func homeServiceCall(){
let urlStr = "https://dev.anyemi.com/webservices/anyemi/getfinancer"
let url = URL(string: urlStr)
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
guard let respData = data else {
return
}
guard error == nil else {
print("error")
return
}
do{
let jsonObj = try JSONSerialization.jsonObject(with: respData, options: .allowFragments) as! [String: Any]
print("the home json is \(jsonObj)")
let financerArray = jsonObj["financer"] as! [[String: Any]]
print("homw financerData \(financerArray)")
for financer in financerArray {
let id = financer["id"] as! String
let pic = financer["icon"] as? String
let type = financer["tpe"] as! String//dob
print(id)
print(type)
print("the icons \(String(describing: pic))")
self.itemsArray.append(JsonData(icon: pic ?? "", tpe: type))
print("online images bug \(self.itemsArray.count)")
}
DispatchQueue.main.async {
self.collectionView.reloadData()
}
}
catch {
print("catch error")
}
}).resume()
}
#IBAction func signOutButton(_ sender: Any) {
print("signout tapped")
KeychainWrapper.standard.remove(key: "Uid")
}
}
if i use MyNavigationController with is initial then sidemenu and didSelectItemAt are working but when i am coming from sinin both are not responding please help me in the above issue.
This is happening due to you are not embedding navigation controller to your HomeViewController. Update your code in sign-in as follow:
let homeVC = self.storyboard?.instantiateViewController(withIdentifier: "HomeViewController") as! HomeViewController
let navigationController = UINavigationController(rootViewController: homeVC)
let appDelagate = UIApplication.shared.delegate
appDelagate?.window??.rootViewController = navigationController

HTML Formatting not working with UILabel in swift

I have used this code to formatting HTML content on UILabel
var htmlToAttributedString: NSAttributedString? {
do {
guard let data = data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
My HTML Content Like:
("<p>My Name is <b>Ayush</b> <I>Bansal</I></p>")
When I used above code for formatting then I get output like (My Name is Ayush Bansal).
But I want my output will be like this (My Name is Ayush Bansal)
you can use this extension
extension String {
func convertToAttributed(_ defaultFont: UIFont, textColor: UIColor ) -> NSAttributedString? {
guard let data = "".replacingOccurrences(of: "\n", with: "<br>").data(using: .utf8, allowLossyConversion: false) else { return nil }
guard let attributedString = try? NSMutableAttributedString(data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
else { return nil }
attributedString.enumerateAttribute(NSAttributedString.Key.font,
in: NSRange(location: 0, length: attributedString.length),
options: NSAttributedString.EnumerationOptions(rawValue: 0))
{ (value, range, _) -> Void in
if let oldFont = value as? UIFont {
var newFont = defaultFont
let isBold = oldFont.fontName.lowercased().contains("bold")
let isItalic = oldFont.fontName.lowercased().contains("italic")
if isBold && isItalic {
newFont = UIFont.bolditalicFont(ofSize: 14)
} else if isBold {
newFont = UIFont.boldFont(ofSize: 14)
} else if isItalic {
newFont = UIFont.italicFont(ofSize: 14)
}
attributedString.removeAttribute(NSAttributedString.Key.font, range: range)
attributedString.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: textColor, range: range)
}
}
}
}
usage:
yourLabel.attributedText = string.convertToAttributed(font, textColor: textcolor)

Resizing UILabel with HTML data

I created a UILabel and synced its font size with a seekbar and loaded my html formatted text onto the UILabel. Unfortunately, the format gets removed if I change the font size of my UILabel using seekbar.
I used this approach, from garie, that was answered from another thread
private func getHtmlLabel(text: String) -> UILabel {
let label = UILabel()
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.attributedString = stringFromHtml(string: text)
return label
}
private func stringFromHtml(string: String) -> NSAttributedString? {
do {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
}
return nil
}
Link: Swift: Display HTML data in a label or textView
Is there any approach I could use to retain the my html formatted text?
EDIT #1:
This is how I resize my UILabel.
#IBOutlet weak var textLabel: UILabel!
#IBAction func resizeText(_ sender: UISlider) {
textLabel.font = UIFont.systemFont(ofSize: CGFloat(sender.value) * 20.0)
}
The HTML data I'm passing onto my UILabel:
<html><body><b>hello world</b></body></html>
This is the formatted HTML data on UILabel:
After resizing the UILabel, it loses its format:
EDIT #2:
Tried Milan's answer but encountered an error. Unresolved identifier in NSAttributedStringKey
Here's my code:
import UIKit
class GalleryViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
textLabel.attributedText = stringFromHtml()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBOutlet weak var textLabel: UILabel!
#IBAction func resizeText(_ sender: UISlider) {
if let attributedText = textLabel.attributedText {
let newAttributedText = NSMutableAttributedString(attributedString: attributedText)
newAttributedText.setFontSize(newSize: CGFloat(sender.value) * 20.0)
textLabel.attributedText = newAttributedText
}
}
private func stringFromHtml() -> NSAttributedString? {
do {
let string = "<html><body><b>hello world</b></body></html>"
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
if let d = data {
let str = try NSAttributedString(data: d,
options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
return str
}
} catch {
}
return nil
}
}
extension NSMutableAttributedString {
func setFontSize(newSize: CGFloat) {
beginEditing()
self.enumerateAttribute(NSAttributedStringKey.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
if let f = value as? UIFont {
let newFont = f.withSize(newSize)
removeAttribute(NSAttributedStringKey.font, range: range)
addAttribute(NSAttributedStringKey.font, value: newFont, range: range)
}
}
endEditing()
}
}
Setting the font directly messes up your attributed text. You will have to set font size on the attributedText:
#IBAction func resizeText(_ sender: UISlider) {
if let attributedText = textLabel.attributedText {
let newAttributedText = NSMutableAttributedString(attributedString: attributedText)
newAttributedText.setFontSize(newSize: CGFloat(sender.value) * 20.0)
textLabel.attributedText = newAttributedText
}
}
For this to work you will need following extension on NSMutableAttributedString:
extension NSMutableAttributedString {
func setFontSize(newSize: CGFloat) {
beginEditing()
self.enumerateAttribute(NSAttributedStringKey.font, in: NSRange(location: 0, length: self.length)) { (value, range, stop) in
if let f = value as? UIFont {
let newFont = f.withSize(newSize)
removeAttribute(NSAttributedStringKey.font, range: range)
addAttribute(NSAttributedStringKey.font, value: newFont, range: range)
}
}
endEditing()
}
}
Try using UserDefaults to save the the NSAttributedString returning from second function:
1- Hold the attributed text in a variable
let attributedText = stringFromHtml(string: String)
2- Save it in UserDefaults
UserDefaults.standard.set(attributedText, forKey: "attributedText")
And for retrieving it you may use this format to safely unwrap the value:
if let text = UserDefaults.standard.object(forKey: "attributedText") as? NSAttributedString {
label.attributedString = text
}

How do I use json instead of plist to populate TableView

I have a working App which takes data from a pList on a remote server. However, I now want to use json instead of plist and am struggling with understanding how to do this! Any help much appreciated and any examples awesome.
Some selected code - first download of plist and second populating the TableView using the downloaded plist. Note: I have not included ALL the code.
#IBAction func startDownload(sender: AnyObject) {
progressView.hidden = false
let url = NSURL(string: "http://ftp.iphoneData#dittodata.host-ed.me/Annotations/myAnnotationsKalkan.plist")!
downloadTask = backgroundSession.downloadTaskWithURL(url)
downloadTask.resume()
}
func showFileWithPath(path: String){
let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
if isFileFound == true{
let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
viewer.delegate = self
viewer.presentPreviewAnimated(true)
// print("file is found")
}
}
#IBOutlet var progressView: UIProgressView!
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 1
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didFinishDownloadingToURL location: NSURL){
let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = NSFileManager()
let destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/myAnnotationsKalkan.plist.plist"))
if fileManager.fileExistsAtPath(destinationURLForFile.path!){
showFileWithPath(destinationURLForFile.path!)
}
else{
do {
try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
// show file
showFileWithPath(destinationURLForFile.path!)
}catch{
print("An error occurred while moving file to destination url")
}
}
}
// 2
func URLSession(session: NSURLSession,
downloadTask: NSURLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64){
progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
}
func URLSession(session: NSURLSession,
task: NSURLSessionTask,
didCompleteWithError error: NSError?){
downloadTask = nil
progressView.setProgress(0.0, animated: true)
if (error != nil) {
print(error?.description)
}else{
// print("The task finished transferring data successfully")
progressView.hidden = true
}
}
// TableViewController.swift
/ museumTemplate
//
import UIKit
class MyTableViewController: UITableViewController {
var titleData = [String]()
var subTitleData = [String]()
var stateData = [String]()
var codeData = [String]()
var infoData = [String]()
var openData = [String]()
var phoneData = [String]()
var emailData = [String]()
var webData = [String]()
var latData = [Double]()
var lonData = [Double]()
var titleToPass = [String]()
var thisState = [String]()
var stateOrAlpha = ""
var titleText = ""
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = titleText
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let sourcePath = documentsPath.stringByAppendingPathComponent("myAnnotationsKalkan.plist.plist")
if let content = NSArray(contentsOfFile: sourcePath as String){
let descriptor = NSSortDescriptor(key: stateOrAlpha, ascending: true)
let myMuseum = content.sortedArrayUsingDescriptors([descriptor])
for item in myMuseum{
titleData.append(item.objectForKey("title") as! String)
subTitleData.append(item.objectForKey("subtitle") as! String)
infoData.append(item.objectForKey("info") as! String)
phoneData.append(item.objectForKey("phone") as! String)
webData.append(item.objectForKey("web") as! String)
emailData.append(item.objectForKey("email") as! String)
latData.append(item.objectForKey("latitude") as! Double)
lonData.append(item.objectForKey("longitude") as! Double)
}
}
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of rows in the section.
return titleData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("tableCell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell..title and subTitle.
cell.textLabel!.text = titleData[indexPath.row]
return cell
}
i use Alamofire wich is more easier and safe to do Web requests, but here is a code without it:
let urlPath = "YourUrlRequest"
let session = NSURLSession.sharedSession()
let url = NSURL(string: urlPath)!
session.dataTaskWithURL(url) {( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let responseData = data {
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(responseData, options: []) as! NSArray
for dataDict : AnyObject in jsonObject {
let idj: String = dataDict.objectForKey("id") as!String
let namej: String = dataDict.objectForKey("name") as! String
let indicativej: String = dataDict.objectForKey("indicative") as! String
let flagj: String = dataDict.objectForKey("flag") as! String
saveCountryFromWeb(idj, name: namej, indicative: indicativej, flag: flagj)
}
} catch let error as NSError {
print("Failed to load: \(error.localizedDescription)")
}
}
}.resume()
Hope the helps, tell me in case you want a sample with alamofire which i recommend ;)
func retrieveBarcodeData(){
let databaseref = FIRDatabase.database().reference()
databaseref.child("barcodes").queryOrderedByKey().observeEventType(.ChildAdded, withBlock: {
snapshot in
let codig = snapshot.value!["codigo"] as! String
let desc = snapshot.value!["designacao"] as! String
let Url = snapshot.value!["ImageURL"] as! String
barcodes.insert(BarCodeStruct(code: codig, description: desc, ImageURL: Url),atIndex: 0)
self.tableView.reloadData()
})
}
Don't forget to configure your database in firebase, and install firebase with cocoapods and put FIRApp.configure() in your appDelegate didFinishLaunchingWithOptions
I tried this code for downloading a simple json file from a server and it seems to work:
override func viewDidLoad() {
super.viewDidLoad()
let requestURL: NSURL = NSURL(string: "http://ftp.iphoneData#dittodata.host-ed.me/Annotations/testData4.json")!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
if (statusCode == 200) {
print("File downloaded.")
// print(testData4.json)
do{
let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments)
if let users = json["users"] as? [[String: AnyObject]] {
for user in users {
if let name = user["name"] as? String {
if let subtitle = user["subtitle"] as? String {
print(name,subtitle)
}
}
}
}
}catch {
print("Error with Json: \(error)")
}
}
}
task.resume()
}