I was trying to load images from a web service to my tableview. But the images are refreshed and same image rotate in every cell. I think the problem is due to not implementing caching in proper way. I tried lot of stuff. But no luck..
import UIKit
class NewsTableViewController: UITableViewController {
var SLAFImages = [String]()
var SLAFHeading = [String]()
var SLAFText = [String]()
var SLAFCount = [Int]()
#IBOutlet weak var btnAction: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
let reposURL = NSURL(string: "https://www.helitours.lk/test.html")
// 2
do{
if let JSONData = NSData(contentsOfURL: reposURL!) {
// 3
if let json = try NSJSONSerialization.JSONObjectWithData(JSONData, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary {
// 4
if let reposArray = json["items"] as? [NSDictionary] {
// 5
for item in reposArray {
if let name = item.valueForKey("title") {
SLAFHeading.append(name as! String)
}
if let Imgname = item.valueForKey("main_image") {
let urlimg=("http://airforce.lk/"+(Imgname as! String)) as String;
SLAFImages.append(urlimg)
}
}
}
}
}
}catch{}
let infoImage = UIImage(named: "crest png.png")
let imgWidth = infoImage?.size.width
let imgHeight = infoImage?.size.height
let button:UIButton = UIButton(frame: CGRect(x: 0,y: 0,width: imgWidth!, height: imgHeight!))
button.setBackgroundImage(infoImage, forState: .Normal)
//button.addTarget(self, action: Selector("openInfo"), forControlEvents: UIControlEvents.TouchUpInside)
SLAFCount=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
SLAFText = ["While they like to munch on underwater plants, you might ",
"While they like to munch on underwater plants, you might ",
"While they like to munch on underwater plants, you might "]
//SLAFImages = ["Img1.jpg","Img2.jpg","Img3.jpg"]
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return SLAFHeading.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell =
self.tableView.dequeueReusableCellWithIdentifier(
"NewsTableCell", forIndexPath: indexPath)
as! NewsTableViewCell
let row = indexPath.row
cell.NewsHeading.font =
UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline)
cell.NewsHeading.text = SLAFHeading[row]
if let url = NSURL(string: SLAFImages[row]) {
let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, NSHTTPURLResponse, error) -> Void in
if error != nil {
print("thers an error in the log")
} else {
dispatch_async(dispatch_get_main_queue()) {
cell.NewsImage.image = UIImage(data: data!)
}
}
}
task.resume()
}
cell.NewsCount.text=String(SLAFCount[row])
cell.layoutIfNeeded()
return cell
}
Download image in Table view cell
Better way
this code will not increase more memory use of app.
//Initialize your catch variable
var cache = NSCache()
// MARK: - Private Image Download Block here
private func downloadPhoto(url: NSURL, completion: (url: NSURL, image: UIImage) -> Void) {
dispatch_async(downloadQueue, { () -> Void in
if let data = NSData(contentsOfURL: url) {
if let image = UIImage(data: data) {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
cache.setObject(image, forKey: url)
completion(url: url, image: image)
})
}
}
})
}
//Call this Function from Table view
//Step 1
// Checking here Image inside Catch
let imageurl = NSURL(string:”Image URL here”)
let myimage = cache.objectForKey(imageurl!) as? UIImage
//Step 2
// Downloading here Promotion image
if myimage == nil {
downloadPhoto(imageurl!, completion: { (url, image) -> Void in
let indexPath_ = self.tblView.indexPathForCell(cell)
if indexPath.isEqual(indexPath_) {
cell.myImageView.image = image
}
})
}
I hope this will help you.
Related
Pictures in my tableView are shifting around and are not being displayed on the correct posts after reloading the tableView. I cannot figure how to fix this.
https://i.stack.imgur.com/4hUbYm.jpg
The image above would be the normal image, however sometimes I get:
https://i.stack.imgur.com/PVEVrm.png
I've also did the prepareForReuse() function in the custom cell class but still doesn't work.
Here is the source code:
class UserPostsController: UIViewController, UITableViewDataSource, UITableViewDelegate {
#IBOutlet weak var userPostsTable: UITableView!
var images : [UIImage] = []
var descriptions : [String] = []
var likes : [String] = []
var dislikes : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.font: UIFont(name: "Pacifico", size: 30)!]
userPostsTable.dataSource = self
userPostsTable.delegate = self
let postQuery = PFQuery(className: "Post")
postQuery.whereKey("userid", equalTo: PFUser.current()?.objectId as Any)
postQuery.findObjectsInBackground { (objects, error) in
if let posts = objects {
for post in posts {
if let descripiton = post["description"] {
self.descriptions.append(descripiton as! String)
}
if let l = post["likes"] {
self.likes.append(l as! String)
}
if let d = post["dislikes"] {
self.dislikes.append(d as! String)
}
if let imageFile = post["imageFile"] as? PFFile {
imageFile.getDataInBackground(block: { (data, error) in
if let imageData = data {
if let image = UIImage(data: imageData) {
self.images.append(image)
}
}
self.userPostsTable.reloadData()
})
}
}
}
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = userPostsTable.dequeueReusableCell(withIdentifier: "userPostCell", for: indexPath) as? UserPostsTableViewCell {
cell.descriptionLabel.text = descriptions[indexPath.row]
cell.numerLikes.text = "\(likes[indexPath.row]) likes"
cell.numberDislikes.text = "\(dislikes[indexPath.row]) dislikes"
cell.postImage.image = images[indexPath.row]
cell.selectionStyle = .none
return cell
}
return UITableViewCell()
}
I think you problem is here:
if let imageFile = post["imageFile"] as? PFFile {
imageFile.getDataInBackground(block: { (data, error) in
if let imageData = data {
if let image = UIImage(data: imageData) {
self.images.append(image)
}
}
self.userPostsTable.reloadData()
})
You are starting background tasks to get images data.
Any of these tasks could finish first, please debug your array and you might find that the images are not in the desired order.
Here is an apple sample project that might help you properly load those images in background.
https://developer.apple.com/library/archive/samplecode/LazyTableImages/Introduction/Intro.html
In my application, I download a JSON file off of the internet and fill up a UITableView with items from the file. It does work well, and there are no problems or errors, but the scrolling performance is very laggy, and the UI glitches out a tiny bit.
I assume this is because of the images that I'm downloading from the JSON file, so I've looked into multi-threading, but I don't think I am doing it right because it does load much faster, but scrolling performance is still the same as before.
Can somebody please tell me how to fix this? This UITableView is the most important thing in the app, and I have been spending much time on trying to fix it. Thank you!
Here is my code-
import UIKit
class ViewController: UIViewController, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var nameArray = [String]()
var idArray = [String]()
var ageArray = [String]()
var genderArray = [String]()
var descriptionArray = [String]()
var imgURLArray = [String]()
let myActivityIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
final let urlString = "https://pbsocfilestorage.000webhostapp.com/jsonDogs.json"
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithURL()
// Activity Indicator
myActivityIndicator.center = view.center
myActivityIndicator.hidesWhenStopped = true
myActivityIndicator.startAnimating()
view.addSubview(myActivityIndicator)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func downloadJsonWithURL() {
let url = NSURL(string:urlString)
URLSession.shared.dataTask(with: (url as? URL)!, completionHandler: {(data, response, error) ->
Void in
print("Good so far...")
if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary {
print(jsonObj!.value(forKey: "dogs"))
if let dogArray = jsonObj!.value(forKey: "dogs") as? NSArray {
print("Why u no work!")
for dog in dogArray {
if let dogDict = dog as? NSDictionary {
if let name = dogDict.value(forKey: "name") {
self.nameArray.append(name as! String)
}
if let name = dogDict.value(forKey: "id") {
self.idArray.append(name as! String)
}
if let name = dogDict.value(forKey: "age") {
self.ageArray.append(name as! String)
}
if let name = dogDict.value(forKey: "gender") {
self.genderArray.append(name as! String)
}
if let name = dogDict.value(forKey: "image") {
self.imgURLArray.append(name as! String)
}
if let name = dogDict.value(forKey: "description") {
self.descriptionArray.append(name as! String)
}
OperationQueue.main.addOperation ({
self.myActivityIndicator.stopAnimating()
self.tableView.reloadData()
})
}
}
}
}
}).resume()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nameArray.count
}
func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return UITableViewAutomaticDimension;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let imgURL = NSURL(string: imgURLArray[indexPath.row])
let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell") as! TableViewCell
URLSession.shared.dataTask(with: (imgURL as! URL), completionHandler: {(data, resp, error) -> Void in
if (error == nil && data != nil) {
OperationQueue.main.addOperation({
cell.dogNameLabel.text = self.nameArray[indexPath.row]
cell.idLabel.text = self.idArray[indexPath.row]
cell.ageLabel.text = self.ageArray[indexPath.row]
cell.genderLabel.text = self.genderArray[indexPath.row]
print("Cell info was filled in!")
if imgURL != nil {
let data = NSData(contentsOf: (imgURL as? URL)!)
cell.dogImage.image = UIImage(data: data as! Data)
}
})
}
}).resume()
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDog" {
if let indexPath = self.tableView.indexPathForSelectedRow{
let detailViewController = segue.destination as! DetailViewController
detailViewController.imageString = imgURLArray[indexPath.row]
detailViewController.nameString = nameArray[indexPath.row]
detailViewController.idString = idArray[indexPath.row]
detailViewController.ageString = ageArray[indexPath.row]
detailViewController.descriptionString = descriptionArray[indexPath.row]
detailViewController.genderString = genderArray[indexPath.row]
}
}
}
}
There is a big mistake. You are loading data with dataTask but you aren't using that returned data at all. Rather than you are loading the data a second time with synchronous contentsOf. Don't do that.
And don't update the labels in the asynchronous completion block. The strings are not related to the image data.
This is more efficient:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let imgURL = URL(string: imgURLArray[indexPath.row])
let cell = tableView.dequeueReusableCell(withIdentifier: "reusableCell", for: indexPath) as! TableViewCell
cell.dogNameLabel.text = self.nameArray[indexPath.row]
cell.idLabel.text = self.idArray[indexPath.row]
cell.ageLabel.text = self.ageArray[indexPath.row]
cell.genderLabel.text = self.genderArray[indexPath.row]
print("Cell info was filled in!")
URLSession.shared.dataTask(with: imgURL!) { (data, resp, error) in
if let data = data {
OperationQueue.main.addOperation({
cell.dogImage.image = UIImage(data: data)
})
}
}.resume()
return cell
}
Note: You are strongly discouraged from using multiple arrays as data source. It's very error-prone. Use a custom struct or class. And create imgURLArray with URL instances rather than strings. This is also much more efficient.
Nevertheless, you should use a download manager which caches the images and cancels downloads if a cell goes off-screen. At the moment each image is downloaded again when the user scrolls and cellForRow is called again for this particular cell.
import UIKit
import Alamofire
protocol VideoModelDelegate{
func dataReady()
}
class VideoModel: NSObject {
let API_KEY = ""
let UPLOADS_PLAYLIST_ID = ""
var videoArray = [Video]()
var delegate:VideoModelDelegate?
func getFeedVideos() -> [Video] {
Alamofire.request(.GET, "",parameters: ["part":"snippet", "playlistId":UPLOADS_PLAYLIST_ID ,"key":API_KEY],
encoding: ParameterEncoding.URL, headers: nil).responseJSON {(response) -> Void in
if let JSON = response.result.value{
var arrayOfVideos = [Video]()
for video in JSON["items"] as! NSArray {
print(video)
let videoObj = Video()
videoObj.videoId = video.valueForKeyPath("snippet,resourceId, videoId")
String
videoObj.videoTitle = video.valueForKeyPath("snippet.title") as! String
videoObj.videoDescription = video.valueForKeyPath("snippet.description") as!
String
videoObj.videoThumbnailUrl = video.valueForKeyPath("snippet.thumbnails.maxres.url") as! String
arrayOfVideos.append(videoObj)
}
self.videoArray = arrayOfVideos
if self.delegate != nil {
self.delegate!.dataReady()
}
}
}
}
func getVideos() -> [Video] {
var videos = [Video]()
let video1 = Video()
video1.videoId = ""
video1.videoTitle = ""
videos.append(video1)
return videos
}
}
[Additional Errors][Error]1How to make my viewcontroller conform to protocol "UITableViewDataSource, and Video Mode Delegate"?
I have tried a number of suggested changes in the previous threads, but nothing got me through, Please help me out.
Thanks in advance
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource,
UITableViewDelegate, VideoModelDelegate ERROR- Type 'tab' does not conform to protocol 'UITableViewDataSource'
{
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
let videoThumbnailUrlString =
videos[indexPath.row].videoThumbnailUrlString;)ERROR:Expected Expression
let videoThumbnailUrl != nil ERROR-'!= is not a prefix unary operator'
and 'Type annotation missing in pattern'
{
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}
}
}
re
It looks as though you haven't closed the method didReceivedMemoryWarning: and the tableview delegate methods are then effectively inside this method causing your issue. Add a closing bracket and it should be fine:
Update: Here is the updated code. There was some more formatting issues with brackets and an error with your if statement in the cellForRowAtIndex:
import UIKit
import Alamofire
class tab: UIViewController, UITableViewDataSource, UITableViewDelegate, VideoModelDelegate {
#IBOutlet weak var table: UITableView!
#IBOutlet weak var name: UILabel!
var videos : [Video] = [Video]()
var selectedVideo:Video?
let model:VideoModel = VideoModel()
var arrRes = [[String:AnyObject]]() //Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
self.model.delegate = self
//self.videos = model.getVideos()
model.getFeedVideos()
self.table.dataSource = self
self.table.delegate = self
/*Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").response { (req, res, data, error) -> Void in
print(res)
let outputString = NSString(data: data!, encoding:NSUTF8StringEncoding)
print(outputString)
}
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { response in
if let swiftyJsonVar = response.data
{
print("swiftyJsonvar:\(swiftyJsonVar)")
}
}*/
Alamofire.request(.GET, "http://online.m-tutor.com/mtutor/gateway/mtutorAPI_1.php?type=university").responseJSON { (responseData) -> Void in
let swiftyJsonVar = JSON(responseData.result.value!)
if let resData = swiftyJsonVar["contacts"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.table.reloadData()
}
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} //ADDED CLOSING BRACKET HERE
func dataReady(){
self.videos = self.model.videoArray
self.table.reloadData()
}
func tableView(table: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) ->
CGFloat {
return(self.view.frame.size.width / 320) * 180
}
func tableview(table:UITableView, numberOfRowsInSection section: Int ) ->Int{
return videos.count
}
func tableVie(table: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell{
let cell = table.dequeueReusableCellWithIdentifier("jsonCell")!
let videoTitle = videos[indexPath.row].videoTitle
let label = cell.viewWithTag(2) as! UILabel
label.text = videoTitle
//cell.textLabel?.text = videoTitle
//CHANGE THESE TWO LINES:
//let videoThumbnailUrlString = videos[indexPath.row].videoThumbnailUrlString;)
//if let videoThumbnailUrl != nil {
//TO THIS:
if let videoThumbnailUrl = videos[indexPath.row].videoThumbnailUrlString {
let request = NSURLRequest(URL: videoThumbnailUrl!)
let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: {(data:NSData?, response:NSURLResponse?, error:NSError) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let imageView = cell.viewWithTag(1) as! UIImageView
imageView.image = UIImage(data: data!)
})
})
dataTask.resume()
}
return cell
}
func tableView(table: UITableView, didSelectRowAtIndexPath indexpath: NSIndexPath){
self.selectedVideo = self.videos[indexpath.row]
self.performSegueWithIdentifier("toVDVC", sender: self)
}
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let detailViewController = segue.destinationViewController as! VDViewController
detailViewController.selectedVideo = self.selectedVideo
}
}
Below is the my code!!!
import UIKit
class myhomefeedViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var tableData = []
var imageCache = [String:UIImage]()
var imageCache1 = [String:UIImage]()
var imageCache2 = [String:UIImage]()
#IBOutlet var appsTableView: UITableView!
var refreshControl:UIRefreshControl!
let PageSize = 5
#IBOutlet var tableViewFooter:Reload!
var loading = false
override func viewDidLoad() {
super.viewDidLoad()
self.tableViewFooter.hidden = true
loadmyhomefeeddata(0, size: PageSize)
self.refreshControl = UIRefreshControl()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
self.appsTableView.addSubview(refreshControl)
}
func refresh(refreshControl: UIRefreshControl) {
loadmyhomefeeddata(0, size: PageSize)
refreshControl.endRefreshing()
}
func loadSegment(offset:Int, size:Int) {
if (!self.loading) {
self.setLoadingState(true)
if currentpage < toPage {
}
else if currentpage > toPage
{
self.setLoadingState(false)
}
}
else
{
println("Not Loading")
}
}
func setLoadingState(loading:Bool) {
self.loading = loading
self.tableViewFooter.hidden = !loading
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
if (maximumOffset - currentOffset) <= 40 {
loadSegment(currentpage, size: tableData.count)
}
}
// pull to refresh list
#IBAction func writeyouridea(sender: AnyObject) {
let viewController=self.storyboard?.instantiateViewControllerWithIdentifier("writeyouridea") as? UIViewController
self.presentViewController(viewController!, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return tableData.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myhomefeedcell", forIndexPath: indexPath) as! myhomefeedTableViewCell
// Configure the cell...
if let rowData: NSDictionary = self.tableData[indexPath.row] as? NSDictionary,
urlString = rowData["imgfile"] as? String,
imgURL = NSURL(string: urlString),
// imgData = NSData(contentsOfURL: imgURL),
countryString = rowData["cflag"] as? String,
countryimgURL = NSURL(string: countryString),
// countryimgData = NSData(contentsOfURL: countryimgURL),
ideaimageString = rowData["ideapicture"] as? String,
ideaimageURL = NSURL(string: ideaimageString),
// ideaimagedata = NSData(contentsOfURL: ideaimageURL),
userfullname = rowData["name"] as? String,
category = rowData["categoryname"] as? String,
ideadesc = rowData["idea"] as? String,
time = rowData["createddate"] as? String,
ideatitle = rowData["title"] as? String {
cell.ideadesc.text = ideadesc
cell.username.text = userfullname
cell.categoryname.text = category
cell.feedimage.image = UIImage(named: "cross")
cell.userimage.image = UIImage(named: "cross")
cell.country.image = UIImage(named: "cross")
cell.title.text = ideatitle
cell.time.text = time
//country
if let countryimg = imageCache1[countryString] {
cell.country.image = countryimg
}
else {
let request: NSURLRequest = NSURLRequest(URL: countryimgURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let imagecountry = UIImage(data: data)
self.imageCache1[countryString] = imagecountry
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
cell.country.image = imagecountry
})
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
//userimage
if let userimg = imageCache2[urlString] {
cell.userimage.image = userimg
}
else {
let request: NSURLRequest = NSURLRequest(URL: imgURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let imageuser = UIImage(data: data)
self.imageCache2[urlString] = imageuser
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
cell.userimage.image = imageuser
})
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
if cell.feedimage.image != nil
{
if let img = imageCache[ideaimageString] {
cell.feedimage.image = img
}
else {
let request: NSURLRequest = NSURLRequest(URL: ideaimageURL)
let mainQueue = NSOperationQueue.mainQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)
self.imageCache[ideaimageString] = image
// Update the cell
dispatch_async(dispatch_get_main_queue(), {
cell.feedimage.image = image
})
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
}
}
return cell
}
func loadmyhomefeeddata(offset:Int, size:Int) {
let rowslimit = size
let urlPath = "url address?noofrowslimit=\(rowslimit)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
if(error != nil) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as? NSDictionary {
if(err != nil) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
// println(jsonResult)
if let results: NSArray = jsonResult["results"] as? NSArray {
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.appsTableView!.reloadData()
})
}
}
})
task.resume()
}
}
Are you trying to have a infinite scroll? If so, you could try the following. First of all, make the task an instance variable of your controller then add the following UIScrollViewDelegate.
override func scrollViewDidScroll(scrollView: UIScrollView) {
// If you are already loading elements, return. This method is called multiple times
if task?.state == .Running { // You could use the isLoading variable instead
return
}
let offSetY = scrollView.contentOffset.y
let triggerY = scrollView.contentSize.height - tableView.frame.size.height
if (offSetY >= triggerY) {
// The offset of elements should be the amount you currently have, and you want to fetch 5 more elements
self.loadmyhomefeeddata(tableData.count, size: 5)
}
}
I have managed to retrieve data from JSON using swiftJSON but I am facing problems when i try to populate tableview. I am new to iOS development, so please bear with me on this. I would appreciate if you could help or provide some ideas ?
Here's the code:
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
}
})
}
task.resume()
}
Here is your complete code for that:
import UIKit
class TableViewController: UITableViewController {
var tableName = [String]()
var tableID = [String]()
override func viewDidLoad() {
super.viewDidLoad()
getContactListJSON()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
self.tableName.append(name)
self.tableID.append(id)
}
dispatch_async(dispatch_get_main_queue(),{
self.tableView.reloadData()
})
})
}
task.resume()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableName.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! TableViewCell
// Configure the cell...
cell.id.text = tableID[indexPath.row]
cell.name.text = tableName[indexPath.row]
return cell
}
}
And HERE is working sample project for you with custom cell.
First declare a local variable NSArray called contactsArray.
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
//Code for downloading data
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
self.contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
[self.tableView reloadData]
})
}
task.resume()
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.contactsArray.count;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
var contacts:NSDictionary = self.contactsArray[indexPath.row];
cell.textLabel?.text = contacts["name"].stringValue
//.......
//.......
return cell
}
Here is a piece of code.
var dataArray = [String]()
override func viewDidLoad(){
super.viewDidLoad()
getContactListJSON()
}
func getContactListJSON(){
let urlString = "http://jsonplaceholder.typicode.com/users"
let urlEncodedString = urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let url = NSURL( string: urlEncodedString!)
var task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, innerError) in
let json = JSON(data: data)
let contactsArray = json.arrayValue
dispatch_async(dispatch_get_main_queue(), {
for contacts in contactsArray
{
let id = contacts["id"].stringValue
let name = contacts["name"].stringValue
println( "id: \(id) name: \(name)" )
self.dataArray.append(name)
}
self.tableView.reloadData()
})
}
task.resume()
}
Here i am taking name. If you want to display id as well, then create a model class for it.