I have a UITableViewController that contains a static UITableView from which you can request quotes and buy or sell a stock. I handle all communications to the backend in a separate ServerCommunicator class. When a request completes, the ServerCommunicator calls the delegate (the tableViewController) which updates the fields in the tableView.
In the main queue, I call tableView.reloadData and display the fields.
The problem is that the fields display immediately but show stale values. When I select a row by clicking on it, however, value is updated.
What am I doing wrong?
class AddStockTableViewController: UITableViewController, ServerCommunicatorDelegate {
………..
override func viewDidLoad() {
super.viewDidLoad()
nameLabel.hidden = true
symbolLabel.hidden = true
quoteLabel.hidden = true
changeLabel.hidden = true
….….
}
#IBAction func getQuoteAction(sender: UIButton) {
if let symbol = getQuoteTextField.text {
serverCommunicator.updateQuote(symbol, delegate: self)
}
}
func didCompleteRequest(data : NSData)
{
quote = parseQuote(data)
self.symbolLabel.text = "(\(self.quote.symbol))"
self.nameLabel.text = self.quote.name
self.quoteLabel.text = "\(self.quote.currentPrice)"
self.changeLabel.text = “\(self.quote.change)"
…….
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
self.nameLabel.hidden = false
self.symbolLabel.hidden = false
self.quoteLabel.hidden = false
………
}
}
class ServerCommunicator
{
func sendRequest(requestURL : String, requestString : String, delegate : ServerCommunicatorDelegate)
{
if let requestData = requestString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false){
let request = NSMutableURLRequest(URL: NSURL(string: requestURL)!)
request.HTTPMethod = "POST"
let urlSession = NSURLSession.sharedSession()
let task = urlSession.uploadTaskWithRequest(request, fromData: requestData, completionHandler: {(data, response, error) -> Void in
if error != nil {
println(error.localizedDescription)
}
else {
delegate.didCompleteRequest(data)
}
})
task.resume()
} else {
print("Could not encode requestString to data")
}
}
…….
}
There is no such thing as Static TableView Update. All updates are supposed to occur through a cell change, and such a change shall be triggered by some kind of table view or table view cell refresh.
An update not showing up in a UITableViewCell indicate that the cell is cached and not reloading fresh data.
reloadData in the UITableView triggers reloading all table view cells. Make certain that cellForRowAtIndexPath returns fresh data, and that dequeueReusableCellWithIdentifier uses proper id.
Finally, reloading all cells if you change a single one is not best practice. Is it possible to refresh a single UITableViewCell in a UITableView? Yes it is.
Related
I am building a UITableView that is going to have cells with different layouts in them. The cell I am having issues with has a UICollectionView embedded in it that is generated from an API.
The category name and id populate in the cell correctly, but the images in the UICollectionView do not. The images load, but they are not the right ones for that category. Screen capture of how the collection is loading currently
Some of the things I've tried:
Hard-coding the ids for each one of the categories instead of dynamically generating them. When I do this, the correct images load (sometimes but not always) ... and if they do load correctly, when I scroll the images change to wrong ones
The prepareForReuse() function ... I'm not exactly sure where I would put it and what I would reset in it (I have code I believe already kind of nils the image out [code included below])
I have spent a few hours trying to figure this out, but I am stuck ... any suggestions would be appreciated.
My View Controller:
class EcardsViewController: BaseViewController {
#IBOutlet weak var categoryTable: UITableView!
var categories = [CategoryItem]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.categoryTable.dataSource! = self
self.categoryTable.delegate! = self
DispatchQueue.main.async {
let jsonUrlString = "https://*********/******/category"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
if err == nil {
do {
let decoder = JSONDecoder()
let ecardcategory = try decoder.decode(Category.self, from: data)
self.categories = ecardcategory.category
self.categories.sort(by: {$0.title < $1.title})
self.categories = self.categories.filter{$0.isFeatured}
} catch let err {
print("Err", err)
}
DispatchQueue.main.async {
self.categoryTable.reloadData()
}
}
}.resume()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension EcardsViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return categories.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "EcardsCategoriesTableViewCell", for: indexPath) as! EcardsCategoriesTableViewCell
cell.categoryName.text = ("\(categories[indexPath.row].title)**\(categories[indexPath.row].id)")
cell.ecardCatId = String(categories[indexPath.row].id)
return cell
}
}
My Table Cell:
class EcardsCategoriesTableViewCell: UITableViewCell {
#IBOutlet weak var categoryName: UILabel!
#IBOutlet weak var thisEcardCollection: UICollectionView!
var ecardCatId = ""
var theseEcards = [Content]()
let imageCache = NSCache<NSString,AnyObject>()
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
self.thisEcardCollection.dataSource! = self
self.thisEcardCollection.delegate! = self
DispatchQueue.main.async {
let jsonUrlString = "https://**********/*******/content?category=\(self.ecardCatId)"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
if err == nil {
do {
let decoder = JSONDecoder()
let ecards = try decoder.decode(Ecards.self, from: data)
self.theseEcards = ecards.content
self.theseEcards = self.theseEcards.filter{$0.isActive}
} catch let err {
print("Err", err)
}
DispatchQueue.main.async {
self.thisEcardCollection.reloadData()
}
}
}.resume()
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
extension EcardsCategoriesTableViewCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return theseEcards.count > 7 ? 7 : theseEcards.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "EcardCategoriesCollectionViewCell", for: indexPath) as! EcardCategoriesCollectionViewCell
cell.ecardImage.contentMode = .scaleAspectFill
let ecardImageLink = theseEcards[indexPath.row].thumbSSL
cell.ecardImage.downloadedFrom(link: ecardImageLink)
return cell
}
}
Collection View Cell:
class EcardCategoriesCollectionViewCell: UICollectionViewCell {
#IBOutlet weak var ecardImage: UIImageView!
}
Extension to "download" image:
extension UIImageView {
func downloadedFromReset(url: URL, contentMode mode: UIViewContentMode = .scaleAspectFit, thisurl: String) {
contentMode = mode
self.image = nil
// check cache
if let cachedImage = ImageCache.shared.image(forKey: thisurl) {
self.image = cachedImage
return
}
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
ImageCache.shared.save(image: image, forKey: thisurl)
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String, contentMode mode: UIViewContentMode = .scaleAspectFit) {
guard let url = URL(string: link) else { return }
downloadedFromReset(url: url, contentMode: mode, thisurl: link)
}
}
Both UICollectionViewCell and UITableViewCell are reused. As one scrolls off the top of the screen, it is reinserted below the visible cells as the next cell that will appear on screen. The cells retain any data that they have during this dequeuing/requeuing process. prepareForReuse exists to give you a point to reset the view to default values and to clear any data from the last time it was displayed. This is especially important when working with asynchronous processes, such as network calls, as they can outlive the amount of time that a cell is displayed. Additionally, you're doing a lot of non-setup work in awakeFromNib. This method is not called every time a cell is displayed, it is only called the FIRST time a cell is displayed. If that cell goes off screen and is reused, awakeFromNib is not called. This is likely a big reason that your collection views have the wrong data, they're never making their network request when they appear on screen.
EcardsCategoriesTableViewCell:
prepareForReuse should be implemented. A few things need to occur in this method:
theseEcards should be nilled. When a table view scrolls off screen, you want to get rid of the collection view data or else the next time that cell is displayed, it will show the collection view data potentially for the wrong cell.
You should keep a reference to the dataTask that runs in awakeFromNib and then call cancel on this dataTask in prepareForReuse. Without doing this, the cell can display, disappear, then get reused before the dataTask completes. If that is the case, it may replace the intended values with the values from the previous dataTask (the one that was supposed to run on the cell that was scrolled off screen).
Additionally, the network call needs to be moved out of awakeFromNib:
You are only ever making the network call in awakeFromNib. This method only gets called the first time a cell is created. When you reuse a cell, it is not called. This method should be used to do any additional setup of views from the nib, but is not your main entry point in adding data to a cell. I would add a method on your cell that lets you set the category id. This will make the network request. It will look something like this:
func setCategoryId(_ categoryId: String) {
DispatchQueue.main.async {
let jsonUrlString = "https://**********/*******/content?category=\(categoryId)"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
if err == nil {
do {
let decoder = JSONDecoder()
let ecards = try decoder.decode(Ecards.self, from: data)
self.theseEcards = ecards.content
self.theseEcards = self.theseEcards.filter{$0.isActive}
} catch let err {
print("Err", err)
}
DispatchQueue.main.async {
self.thisEcardCollection.reloadData()
}
}
}.resume()
}
}
This will be called in the cellForRowAt dataSource method in EcardsViewController.
EcardCategoriesCollectionViewCell:
This cell has similar issues. You are setting images asynchronously, but are not clearing the images and cancelling the network requests when the cell is going to be reused. prepareForReuse should be implemented and the following should occur within it:
The image on the image view should be cleared or set to a default image.
The image request should be cancelled. This is going to take some refactoring to accomplish. You need to hold a reference to the dataTask in the collection view cell so that you can cancel it when appropriate.
After implementing these changes in the cells, you'll likely notice that the tableview and collection view feel slow. Data isn't instantly available. You'll want to cache the data or preload it some way. That is a bigger discussion than is right for this thread, but it will be your next step.
I would like to know how should I behave if I got several articles in table view controller, which are loaded and parsed from some API. Then I would like to click on some article to view his detail.
Should I load all articles on start up with all data and then pass concrete whole article to next detail table controller or just send article id and in new table controller load again whole one article with passed id?
I think that is much better second method, but have no idea how to do it. Any help? Thanks a lot.
EDIT: added code
MainTableViewController:
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let articleId = articles[indexPath.row].Id
let destination = DetailTableViewController()
destination.articleId = articleId
destination.performSegue(withIdentifier: "Main", sender: self)
}
DetailTableViewController:
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 140
// Vyzkoušíme jestli jsme připojeni do internetu
if Helper.hasConnectivity() {
// Zapneme načítací obrazovku
setLoadingScreen()
// Načteme jídla
loadMainArticles()
} else {
promptAlert(title: "Upozornění", message: "Ujistěte se, že Vaše zařízení je připojené k internetu")
}
}
private func loadMainArticles() {
ApiService.sharedInstance.fetchArticle(part: "GetArticle", articleId: "brananske-posviceni--spravna-lidova-zabava-s-pecenou-husou") { (articles: [Article]) in
self.removeLoadingScreen()
self.tableView.separatorStyle = .singleLine
if articles.count == 0 {
self.promptAlert(title: "Upozornění", message: "Žádná data")
}
self.selectedArticle = articles[0]
self.tableView.reloadData()
}
}
ApiService:
func fetchArticle(part: String, articleId: String, completion: #escaping ([Article]) -> ()) {
var Id = ""
var Title = ""
var Content = ""
var Picture = ""
var PublishDate = ""
let url = NSURL(string: "http://xxx")
URLSession.shared.dataTask(with: url! as URL) { (data, response, error) in
if error != nil {
print(error as Any)
return
}
do {
let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments)
var articles = [Article]()
for dictionary in json as! [[String: AnyObject]] {
.
.
.
let article = Article(Id: Id, Title: Title, Content: Content, Picture: Picture, PublishDate: PublishDate, Categories: Categories)
articles.append(article!)
}
DispatchQueue.main.async(execute: {
completion(articles)
})
}
}.resume()
}
The problem is that when I do the segue after click on row, then should loadMainArticles. The method is triggered, but always stops on URLSession row and immediately jump to resume() and the completion block is never triggered. Is there any reason why?
This is a choice that should be done according to article data model size.
You should pay attention to which data you need to show on TableView single cell and which on Article detail page.
I suppose you to show:
Title and posted hour in TableView
Title, hour, long description, maybe some image in Detail page
In this case i would reccommend you to download only title and hour for each article item, and then, in detail page, download single item details (avoid to download unused content, since user could not open every item).
Otherwise, if amounts of data are similar, download all informations on first connection and open detail page without making any other network request.
I think that is much better second method, but have no idea how to do it.
You need to retrieve article id from TableView selected cell and pass it to DetailPageViewController using prepareForSegue. In DetailPageViewController ViewDidLoad send article id to your backend api and retrieve article details to show.
I'm loading my UITableView from an Api call but although the data is retrieved fairly quickly, there is a significant time delay before it is loaded into the table. The code used is below
import UIKit
class TrackingInfoController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet var table : UITableView?
#IBOutlet var indicator : UIActivityIndicatorView?
#IBOutlet var spinnerView : UIView?
var tableArrayList = Array<TableData>()
struct TableData
{
var dateStr:String = ""
var nameStr:String = ""
var codeStr:String = ""
var regionStr:String = ""
init(){}
}
override func viewDidLoad() {
super.viewDidLoad()
table!.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
spinnerView?.hidden = false
indicator?.bringSubviewToFront(spinnerView!)
indicator!.startAnimating()
downloadIncidents()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func BackToMain() {
performSegueWithIdentifier("SearchToMainSegue", sender: nil)
}
//#pragma mark - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 //BreakPoint 2
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableArrayList.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell
cell.incidentDate.text = tableArrayList[indexPath.row].dateStr
cell.incidentText.text = tableArrayList[indexPath.row].nameStr
cell.incidentCode.text = tableArrayList[indexPath.row].codeStr
cell.incidentLoctn.text = tableArrayList[indexPath.row].regionStr
return cell //BreakPoint 4
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
AppDelegate.myGlobalVars.gIncName = tableArrayList[indexPath.row].nameStr
AppDelegate.myGlobalVars.gIncDMA = tableArrayList[indexPath.row].codeStr
performSegueWithIdentifier("SearchResultsToDetailSegue", sender: nil)
}
func alertView(msg: String) {
let dialog = UIAlertController(title: "Warning",
message: msg,
preferredStyle: UIAlertControllerStyle.Alert)
dialog.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
presentViewController(dialog,
animated: false,
completion: nil)
}
func downloadIncidents()
{
var event = AppDelegate.myGlobalVars.gIncName
var DMA = AppDelegate.myGlobalVars.gIncDMA
if event == "Enter Event Name" {
event = ""
}
if DMA == "Enter DMA" {
DMA = ""
}
let request = NSMutableURLRequest(URL: NSURL(string: "http://incident-tracker-api-uat.herokuapp.com/mobile/events?name=" + event)!,
cachePolicy: .UseProtocolCachePolicy,
timeoutInterval: 10.0)
request.HTTPMethod = "GET"
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if error != nil {
self.alertView("Error - " + error!.localizedDescription)
}
else {
do {
var incidentList: TableData
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options:.AllowFragments) as? Array<Dictionary<String, AnyObject>> {
for item in json {
if let dict = item as? Dictionary<String, AnyObject> {
incidentList = TableData()
if let nameStr = dict["name"] as? String {
incidentList.nameStr = nameStr
}
if let codeStr = dict["dma"] as? String {
incidentList.codeStr = codeStr
}
if let dateStr = dict["supplyOutageStart"] as? String {
let tmpStr = dateStr
let index = tmpStr.startIndex.advancedBy(10)
incidentList.dateStr = tmpStr.substringToIndex(index)
}
if let regionStr = dict["region"] as? String {
incidentList.regionStr = regionStr
}
self.tableArrayList.append(incidentList)
}
}
self.spinnerView?.hidden = true
self.indicator?.stopAnimating()
self.table?.reloadData() //BreakPoint 3
}
}catch let err as NSError
{
self.alertView("Error - " + err.localizedDescription)
}
}
})
task.resume() //BreakPoint 1
}
When the class is run, it hits BreakPoint 1 first and then hits BreakPoint 2 and then quickly goes to BreakPoint 3, it then goes to BreakPoint 2 once more. Then there is a delay of about 20 to 30 seconds before it hits Breakpoint 4 in cellForRowAtIndexPath() and the data is loaded into the UITableView. The view is displayed quickly afterwards.
The data is retrieved quite quickly from the Web Service so why is there a significant delay before the data is then loaded into the tableView? Is there a need to thread the Web Service method?
You are getting server response in a background thread so you need to call the reloadData() function on the UI thread. I am suspecting that the wait time can vary depending on whether you interact with the app, which effectively calls the UI thread, and that's when the table actually displays the new data.
In a nutshell, you need to wrap the self.table?.reloadData() //BreakPoint 3 with
dispatch_async(dispatch_get_main_queue()) {
// update some UI
}
The final result would be
Pre Swift 3.0
dispatch_async(dispatch_get_main_queue()) {
self.table?.reloadData()
}
Post Swift 3.0
DispatchQueue.main.async {
print("This is run on the main queue, after the previous code in outer block")
}
The table view should begin to reload in a fraction of a second after you call tableView.reloadData().
If you make UI calls from a background thread, however, the results are "undefined". In practice, a common effect I've seen is for the UI changes to take an absurdly long time to actually take effect. The second most likely side-effect is a crash, but other, strange side-effects are also possible.
The completion handler for NSURLSession calls is run on a background thread by default. You therefore need to wrap all your UI calls in a call to dispatch_async(dispatch_get_main_queue()) (which is now DispatchQueue.main.async() in Swift 3.)
(If you are doing compute-intensive work like JSON parsing in your closure it's best to do that from the background so you don't block the main thread. Then make just the UI calls from the main thread.)
In your case you'd want to wrap the 3 lines of code marked with "breakpoint 3" (all UI calls) as well as the other calls to self.alertView()
Note that if you're sure the code in your completion closure is quick you can simply wrap the whole body of the closure in a call to dispatch_async(dispatch_get_main_queue()).
Just make sure you reload your tableview in inside the Dispatch main async, just immediately you get the data
Im a just starting with programming apps in Xcode 7 / Swift 2.0
Im am pretty far with developing my ideas, but I can't seem to get the error handling to work.
The viewcontroller it concerns is presenting dates where and when our band plays.
In this Viewcontroller I call Json data from our online server and parse it into a tableview. It all works. But i want the following things to happen too.
If there is no connection whatsoever (wifi/4G/3G) perform a segue (No Connection)
If the server or the php script is unreachable, perform a segue (server error
)
If there is no data available (as in Empty Array) Just give a message "There are no dates set."
The Json I get from my PHP script:
(
{
date = "some date";
description = "Some description";
location = "Some location";
others = "some details";
showtime = "some time";
},
{
date = "some date";
description = "Some description";
location = "Some location";
others = "some details";
showtime = "some time";
}
)
This is the ViewController
import UIKit
class GigsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var gigsdata: NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
let logo = UIImage(named: "where_is_header_navigationController.jpg")
let imageView = UIImageView(image:logo)
self.navigationItem.titleView = imageView
func dataOfJson(url: String) -> NSArray {
let gigsdata = NSData(contentsOfURL: NSURL(string: url)!)
let jsonArray: NSArray = try! NSJSONSerialization.JSONObjectWithData(gigsdata!, options: .MutableContainers) as! NSArray
return jsonArray
}
gigsdata = dataOfJson("http://www.mydomain.eu/app/myscript.php")
}// end of viewDidLoad
// MARK: Table View Delegate Methods
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if gigsdata.count != 0 {
return gigsdata.count
} else {
return 1
}
}
func allowMultipleLines(tableViewCell:UITableViewCell) {
tableViewCell.textLabel?.numberOfLines = 0
tableViewCell.textLabel?.lineBreakMode = NSLineBreakMode.ByWordWrapping
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("GigsCell")! as UITableViewCell
// setting the text color
cell.textLabel?.textColor = UIColor.whiteColor()
//Getting the JSON data and turn it into objects
let maingigsdata = (gigsdata[indexPath.row] as! NSDictionary)
//setting constants for the detailview
let gigsDate = maingigsdata["date"] as! String
let gigsLocation = maingigsdata["location"] as! String
// Setting the number of lines per row
cell.textLabel!.numberOfLines = 2
// Filling the cell with data
cell.textLabel!.text = ("\(gigsDate) \n\(gigsLocation)")
// setting the beackground color when selected
let backgroundView = UIView()
backgroundView.backgroundColor = UIColor.darkGrayColor()
cell.selectedBackgroundView = backgroundView
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Like i said, im fairly new to this, so please dont go around and name all kinds of proceduresm, functions or things like that.
Please don't think that I don't try myself, but 'm stuck now for two weeks.
The thing I saw a lot on videos and tutorials was the DO TRY CATCH thing.
But implementing that as good as I can gave me just all kinds of errors, so I must be doing something wrong there.
I hope that there is someone out there who can help me out and make me a lot wiser as I am today!
You should use NSURLRequest or some lib like Alamofire to fetch the data. NSData contentsOfURL is not asynchronous and in your case blocks the main thread. I wonder if you can compile your code as NSData contentOfURL throws and exception, which must be catched. Check the domain of NSError object, which is thrown. It can be e.g. NSURLErrorDNSLookupFailed, NSURLErrorDomain, NSURLErrorNotConnectedToInternet, NSURLErrorInternationalRoamingOff.
https://github.com/Alamofire/Alamofire
To detech the connection type:
Detect carrier connection type (3G / EDGE / GPRS)
Example of the error handling based on your code:
do {
// Blocks your UI if you do this in the main thread!
let gigsdata = NSData(contentsOfURL: NSURL(string: url)!)
}
catch let error as! NSError {
if error.domain == NSURLErrorNotConnectedToInternet {
// If you do the data fetch using the background queue then this must be dispatched to the main queue:
performSegueWithIdentifier("noInternet", sender: self)
}
}
For the 1st and 2nd issue I came up with the following working code:
// performing a first check if there is an connection based on the HTTPStatusCode 200
Alamofire.request(.GET, "http://www.google.com")
.responseJSON { response in
if response.response?.statusCode == 200 {
print("Code is 200 and good")
}else{
print("Code is not 200 and therefor bad")
self.performSegueWithIdentifier("NoConnectionSegue", sender: self)
}
}
I implemented the code in the first view controller of my app and the 'NoConnectionSegue' is a view controller that "blocks" the whole screen with a message that the app is not usable without an internet connection and a friendly request to close the app and try later.
Of course the url "google.com" can be replaced with your own domain.
For the 3rd issue I had the following solution.
The viewcontroller is a TableView with cells populated by a json file on a remote server. At the end of the viewDidLoad I check if the array.count is less then 1.
If so, then perform a segue to a new viewcontroller of the kind: "Present Modally" and the presentation: "Over current context".
This way I don't get the navigationbar that I used in the previous Tableview.
Leaving the original Tableview controller with one empty cell invisable in the background.
It might not be the cleanest and the best way. But at least I got what I wanted.
the code:
// check if there are any gigs, otherwise perform segue to NoGigs
if self.arrRes.count <= 1 {
self.performSegueWithIdentifier("NoGigsSegue", sender: self)
}
I'm querying images from my Parse backend, and displaying them in order in a UITableView. Although I'm downloading and displaying them one at a time, they're appearing totally out of order in my table view. Each image (album cover) corresponds to a song, so I'm getting incorrect album covers for each song. Would someone be so kind as to point out why they're appearing out of order?
class ProfileCell: UITableViewCell {
#IBOutlet weak var historyAlbum: UIImageView!
}
class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var historyAlbums = [PFFile]()
var albumCovers = [UIImage]()
// An observer that reloads the tableView
var imageSet:Bool = false {
didSet {
if imageSet {
// Reload tableView on main thread
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
dispatch_async(dispatch_get_main_queue()) { // 2
self.tableView.reloadData() // 3
}
}
}
}
}
// An observer for when each image has been downloaded and appended to the albumCovers array. This then calls the imageSet observer to reload tableView.
var dataLoaded:Bool = false {
didSet {
if dataLoaded {
let albumArt = historyAlbums.last!
albumArt.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data: imageData)
self.albumCovers.append(image!)
}
} else {
println(error)
}
self.imageSet = true
})
}
self.imageSet = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Queries Parse for each image
var query = PFQuery(className: "Songs")
query.whereKey("user", equalTo: PFUser.currentUser()!.email!)
query.orderByDescending("listenTime")
query.limit = 20
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
if let albumCover = object["albumCover"] as? PFFile {
// Appending each image to albumCover array to convert from PFFile to UIImage
self.historyAlbums.append(albumCover)
}
self.dataLoaded = true
}
}
} else {
println(error)
}
self.dataLoaded = false
})
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var profileCell = tableView.dequeueReusableCellWithIdentifier("ProfileCell", forIndexPath: indexPath) as! ProfileCell
profileCell.historyAlbum.image = albumCovers[indexPath.row]
return profileCell
}
}
}
The reason you are getting them out of order is that you are firing off background tasks for each one individually.
You get the list of objects all at once in a background thread. That is perfectly fine. Then once you have that you call a method (via didset) to iterate through that list and individually get each in their own background thread. Once each individual thread is finished it adds it's result to the table array. You have no control on when those background threads finish.
I believe parse has a synchronous get method. I'm not sure of the syntax currently. Another option is to see if you can "include" the image file bytes with the initial request, which would make the whole call a single background call.
Another option (probably the best one) is to have another piece of data (a dictionary or the like) that marks a position to each of your image file requests. Then when the individual background gets are finished you know the position that that image is supposed to go to in the final array. Place the downloaded image in the array at the location that the dictionary you created tells you to.
That should solve your asynchronous problems.