Loading Thumbnails with YouTube Data API - json

I'm using the YouTube API and Alamofire to show videos for my YouTube channel. I'm having an issue that the thumbnails for the videos are messing up when scrolling. Like this:
I used Apple videos for the example. For some reason, the colors got messed up when creating the GIF, though. But you get the idea. Here are my relevant view controllers
TableViewController
import UIKit
class VideosTableViewController: UITableViewController, VideoModelDelegate {
var videos: [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
override func viewDidLoad() {
super.viewDidLoad()
if tableView.rowHeight == 250 {
tableView.estimatedRowHeight = 250
} else {
tableView.estimatedRowHeight = 96
}
tableView.rowHeight = UITableViewAutomaticDimension
model.getFeedVideo()
self.model.delegate = self
dataReady()
//
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func handleRefresh() {
dataReady()
refreshControl?.endRefreshing()
}
func dataReady() {
print("dataReady()")
self.videos = self.model.videoArray
self.tableView.reloadData()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return videos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Configure the cell...
if indexPath.row == 0 {
var cell : NewVideoTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "New Cell") as! NewVideoTableViewCell
cell.titleLabel.text = videos[indexPath.row].videoTitle
cell.thumbnail.clipsToBounds = true
cell.thumbnail.layer.cornerRadius = 5
let videoThumbnailURLString = videos[indexPath.row].videoThumbnailUrl
let videoThumbnailUrl = NSURL(string: videoThumbnailURLString)
if videoThumbnailUrl != nil {
let request = NSURLRequest(url: videoThumbnailUrl! as URL)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
DispatchQueue.main.async {
cell.thumbnail.image = UIImage(data: data!)
}
})
dataTask.resume()
}
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let videoTitle = videos[indexPath.row].videoTitle
let title = cell.viewWithTag(2) as! UILabel
title.text = videoTitle
let videoThumbnailURLString = videos[indexPath.row].videoThumbnailUrl
let videoThumbnailUrl = NSURL(string: videoThumbnailURLString)
let imageView = cell.viewWithTag(1) as! UIImageView
if videoThumbnailUrl != nil {
let request = NSURLRequest(url: videoThumbnailUrl! as URL)
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in
let imageView = cell.viewWithTag(1) as! UIImageView
DispatchQueue.main.async {
imageView.image = UIImage(data: data!)
}
})
imageView.clipsToBounds = true
imageView.layer.cornerRadius = 3
imageView.layer.borderColor = UIColor.lightGray.cgColor
imageView.layer.borderWidth = 0.1
dataTask.resume()
}
return cell
}
}
}
VideoModel
import UIKit
import Alamofire
protocol VideoModelDelegate {
func dataReady()
}
let API_KEY = "My API Key"
let UPLOADS_PLAYLIST_ID = "My Playlist"
let CHANNEL_ID = "My Channel ID"
let parameters = ["part":"snippet","maxResults":50,"channelId":CHANNEL_ID,"playlistId":UPLOADS_PLAYLIST_ID,"key":API_KEY] as [String : Any]
class VideoModel: NSObject {
var videoArray = [Video]()
var delegate: VideoModelDelegate?
func getFeedVideo() {
Alamofire.request("https://www.googleapis.com/youtube/v3/playlistItems", parameters: parameters, encoding: URLEncoding.default, headers: nil).responseJSON { (response) in
if let JSON = response.result.value {
if let dictionary = JSON as? [String: Any] {
var arrayOfVideos = [Video]()
guard let items = dictionary["items"] as? NSArray else { return }
for items in dictionary["items"] as! NSArray {
print(items)
// Create video objects off of the JSON response
let videoObj = Video()
videoObj.videoID = (items as AnyObject).value(forKeyPath: "snippet.resourceId.videoId") as! String
videoObj.videoTitle = (items as AnyObject).value(forKeyPath: "snippet.title") as! String
videoObj.videoDescription = (items as AnyObject).value(forKeyPath: "snippet.description") as! String
videoObj.videoThumbnailUrl = (items as AnyObject).value(forKeyPath: "snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
}
Video
import UIKit
class Video: NSObject {
var videoID:String = ""
var videoTitle:String = ""
var videoDescription:String = ""
var videoThumbnailUrl:String = ""
}
So, do you see how the thumbnails get are jumpy? Any ideas? Thanks for the help!

Related

Parse the json value and get ID into var in Swift

I have list of company names with IDs. I have used a drop down and showing company name in it by parsing JSON data. uncertainly I am unable to get the ID of the selected item in the drop down menu.
My json data is
{
"success": true,
"message": [
{
"company_name": "ABC",
"id": 1
},
{
"company_name": "JHG",
"id": 10
}
]}
My swift code:
let url = NSURL(string: COMPANY_URL)
URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
// print(jsonObj.value(forKey: "message")!)
if let messageArray = jsonObj.value(forKey: "message") as? NSArray
{
for message in messageArray
{
if let messageDict = message as? NSDictionary
{
if let data = data {
let successmessage = jsonObj.value(forKey: "success") as? Int
if(successmessage == 1)
{
if let company_name = messageDict.value(forKey: "company_name")
{
self.companiesArray.append(company_name as! String)
}
if let company_id = messageDict.value(forKey: "id")
{
self.companyidstr.append(company_id as! Int)
print(self.companyidstr)
}
for messageArray in self.companyidstr
{
print(messageArray)
let btnlabel = Int(self.companyBtn.titleLabel!.text!)
if(btnlabel == Int(messageArray))
{
self.companyidstring = messageArray
print(self.companyidstring)
// THIS IS WHERE IT NEED TO SHOW ID BUT NOT }
}
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
} else
{
}
}
}
}
}
}
}).resume()
My requirement is to show list of company name's to users but when they select any company name,should save in the form of concerned ID of the selected item.
my ENTIRE CODE:
class RegistrationViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var tableView: UITableView!
#IBOutlet weak var companyBtn: UIButton!
final let COMPANY_URL = COMPANY_URL
var companiesArray = [String]()
var companyidstr = [Int]()
var companyidstring: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
downloadCompanyNamesFromDB()
// insertUserDetailsintoDB()
tableView.isHidden = true
self.downloadCompanyNamesFromDB()
//tableView.tableFooterView = UIView()
tableView.dataSource = self
tableView.delegate = self
}
#IBAction func companyBtnClick(_ sender: Any) {
// tableView.isHidden = false
if(tableView.isHidden)
{
animate(toogle: true)
} else
{
animate(toogle: false)
}
}
func animate(toogle: Bool)
{
if(toogle)
{
UIView.animate(withDuration: 0.3)
{
self.tableView.isHidden = false
}
} else{
UIView.animate(withDuration: 0.3)
{
self.tableView.isHidden = true
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return companiesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = companiesArray[indexPath.row]
print(companiesArray)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let companytitle = companiesArray[indexPath.row]
companyBtn.setTitle(companytitle, for: .normal)
print(companytitle)
// print(companiesArray[indexPath.row].id as! String)
// companiesArray = message --> HERE IS THE CODE
animate(toogle: false)
}
func downloadCompanyNamesFromDB()
{
let url = NSURL(string: COMPANY_URL)
URLSession.shared.dataTask(with: (url as?URL)!, completionHandler: {(data,response,error) ->
Void in
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
{
// print(jsonObj.value(forKey: "message")!)
if let messageArray = jsonObj.value(forKey: "message") as? NSArray
{
for message in messageArray
{
if let messageDict = message as? NSDictionary
{
if let data = data {
let successmessage = jsonObj.value(forKey: "success") as? Int
if(successmessage == 1)
{
} else
{
}
}
}
}
}
}
}).resume()
}
}
}
It's better to
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode(Root.self,from:data)
print(res.message)
// MARK: - Empty
struct Root: Codable {
let success: Bool
let message: [Message]
}
// MARK: - Message
struct Message: Codable {
let companyName: String
let id: Int
}
var companiesArray = [Message]()
let url = URL(string: COMPANY_URL)!
URLSession.shared.dataTask(with:url, completionHandler: {(data,response,error) ->
Void in
guard let data = data else { return }
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try! dec.decode(Root.self,from:data)
companiesArray = res.message
print(res.message)
OperationQueue.main.addOperation({
self.tableView.reloadData()
})
}).resume()

How to reload data in UITableview after making second Json call Swift 3

I am making JSON request and if its completed so I am navigating page with JSON data to my table view controller and everything works fine but when I am making second call to load more cells I am not able to reload data and here is the code of my table view controller there I am making second call.
var listData:[String] = []
var videoIDData:[String] = []
var valueKeyData:[String] = []
var nextPageToken:String?
var titleNamee:[String] = []
var videoIDD :[String] = []
var valueKeyy :[String] = []
var PrevPageToken:String?
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return listData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "VideoCell", for: indexPath) as! VideoTableViewCell
cell.videoTitle.text = listData[indexPath.row]
let url = NSURL(string: valueKeyData[indexPath.row])
let dataaa = NSData(contentsOf: url! as URL)
let image = UIImage(data: dataaa! as Data)
cell.videoThumnailImageView.image = image
if (indexPath.row == listData.count - 1)
{
makeGetCall()
}
return cell
}
func makeGetCall() {
// Set up the URL request
var pageToken:String = (pageToken)
let todoEndpoint: String = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50\(pageToken)&playlistId=\(id)_ItOZ8WBF5_SI_SrSN3_F&\(key)"
guard let url = URL(string: todoEndpoint) else {
print("Error: cannot create URL")
return
}
let urlRequest = URLRequest(url: url)
// set up the session
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// make the request
let task = session.dataTask(with: urlRequest) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error calling GET on /todos/1")
print(error)
return
}
guard let responseData = data else {
print("Error: did not receive data")
return
}
// parse the result as JSON, since that's what the API provides
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String : AnyObject] else {
print("error trying to convert data to JSON")
return
}
self.PrevPageToken = jsonObject["prevPageToken"] as? String
self.nextPageToken = jsonObject["nextPageToken"] as? String
if let itemsArray = jsonObject["items"] as? [[String:AnyObject]]{
for snippetArray in itemsArray{
if var snippet = snippetArray["snippet"] as? [String : AnyObject]{
if let titleItems = snippet["title"] as? String{
self.titleNamee += [titleItems]
}
if let thumbnail = snippet["thumbnails"] as? [String : AnyObject]{
if let highValue = thumbnail["high"] as? [String : AnyObject]{
if let urlValueKey = highValue ["url"] as? String{
self.valueKeyy += [urlValueKey]
}
}
}
if let resource = snippet["resourceId"] as? [String : AnyObject]{
if let videoId = resource["videoId"] as? String{
// self.videoIDD.append(videoId)
self.videoIDD += [videoId]
}
}
}
}
}
} catch {
print("error trying to convert data to JSON")
return
}
}
task.resume()
DispatchQueue.main.async{
self.tableView.reloadData()
}
}
}
You are reloading tableView at wrong place you need to reload it inside completion block after the for loop because completion block will call async, so remove your current reload code of tableView and put it after the for loop.
for snippetArray in itemsArray{
if var snippet = snippetArray["snippet"] as? [String : AnyObject]{
if let titleItems = snippet["title"] as? String{
self.titleNamee += [titleItems]
}
if let thumbnail = snippet["thumbnails"] as? [String : AnyObject]{
if let highValue = thumbnail["high"] as? [String : AnyObject]{
if let urlValueKey = highValue ["url"] as? String{
self.valueKeyy += [urlValueKey]
}
}
}
if let resource = snippet["resourceId"] as? [String : AnyObject]{
if let videoId = resource["videoId"] as? String{
// self.videoIDD.append(videoId)
self.videoIDD += [videoId]
}
}
}
}
//Reload your table here
DispatchQueue.main.async{
self.tableView.reloadData()
}
Note: Instead of creating multiple array that you are doing currently what you need to do is make one custom class or struct with all these properties and make array of that custom class or struct objects.
Edit: I haven't looked at that you are calling this method in cellForRowAt don't do that as of cell will be reused and that is the reason you UI getting stuck so remove that calling code from cellForRowAt, if you want to make something like pagination than you can use scrollViewDelegate method like this way.
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if((scrollView.contentOffset.y + scrollView.frame.size.height) == scrollView.contentSize.height)
{
self.makeGetCall()
}
}
Also it its better that you show some process indicator while you are making API request.

How do I download json file from remote saver and save to bundle for offline access

I am able to download a json file from a server and put it into a TableView each time the App is opened. (see code below)
However, I also want to allow offline access using the last file downloaded. So essentially I am having trouble working out how to save the downloaded file for local access offline. Any help (especially examples) much appreciated.
class KalkanTableController: UITableViewController {
var TableData:Array< String > = Array < String >()
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json")
if let path = Bundle.main.path(forResource: "kalkanInfoTest", ofType: "json") {
do {
let jsonData = try NSData(contentsOfFile: path, options: NSData.ReadingOptions.mappedIfSafe)
do {
let jsonResult: NSDictionary = try JSONSerialization.jsonObject(with: jsonData as Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
} catch {}
} catch {}
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let item_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let item_obj = item_list[i] as? NSDictionary
{
if let item_name = item_obj["kalkanInfo"] as? Stri
{
TableData.append(item_name)
print(item_name)
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
DispatchQueue.main.async(execute: {
self.tableView.reloadData()
return
})
}
}
You can try to save your json locally using these methods to save on disk
override func viewDidLoad() {
super.viewDidLoad()
if readKalkanDataFromDisk() {
extract_json(readKalkanDataFromDisk())
} else {
get_data_from_url("http://ftp.MY FILE LOCATION/kalkanInfoTest.json")
}
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
saveKalkanDataOnDisk(kalkanData: data!)
self.extract_json(data!)
})
task.resume()
}
func saveKalkanDataOnDisk(kalkanData: Data) {
do {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentsURL.appendingPathComponent("Kalkan.json")
try kalkanData.write(to: fileURL, options: .atomic)
} catch { }
}
func readKalkanDataFromDisk() -> Data? {
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let filePath = documentsURL.appendingPathComponent("Kalkan.json").path
if FileManager.default.fileExists(atPath: filePath), let data = FileManager.default.contents(atPath: filePath) {
return data
}
return nil
}

Hi there , I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data

I'm new to iOS development and I'm having a hard time populating a tableview embedded in a UIviewcontroller with json data.
''import UIKit
class
FirstViewController:UIViewController,UITableViewDataSource,UITableViewDelegate{
#IBOutlet weak var tableview: UITableView!
var TableData:Array< String > = Array < String >()
var valueToPass:String!
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://www.kaleidosblog.com/tutorial/tutorial.json")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TableData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FirstViewCell", for: indexPath)
cell.textLabel?.text = TableData[indexPath.row]
return cell
}
func get_data_from_url(_ link:String)
{
let url:URL = URL(string: link)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url)
request.httpMethod = "GET"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest, completionHandler: {
(
data, response, error) in
guard let _:Data = data, let _:URLResponse = response , error == nil else {
return
}
self.extract_json(data!)
})
task.resume()
}
func extract_json(_ data: Data)
{
let json: Any?
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
}
catch
{
return
}
guard let data_list = json as? NSArray else
{
return
}
if let countries_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let country_obj = countries_list[i] as? NSDictionary
{
if let country_name = country_obj["country"] as? String
{
if let country_code = country_obj["code"] as? String
{
TableData.append(country_name + " [" + country_code + "]")
}
}
}
}
}
DispatchQueue.main.async(execute: {self.do_table_refresh()})
}
func do_table_refresh()
{
tableview.reloadData()
}
}
you need to set tableView's dataSource and delegate to self.

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()
}