I have a table view where the data is loaded from an API call. I am displayed a Loading Overlay View. I used the following code to set up the loading overall view.
https://coderwall.com/p/su1t1a/ios-customized-activity-indicator-with-swift
But the issue is that I can't seem to hide the overlay view or activity indicator once the table view has been loaded. It just keeps on loading.
To start the activity indicator the following code is used:
ViewControllerUtils().showActivityIndicator(self.view)
To Stop it:
ViewControllerUtils().hideActivityIndicator(self.view)
My API call code is below:
import UIKit
class BioListTableViewController: UITableViewController {
// variable to hold the index value of the cell tapped
var cellTapped = Int()
#IBOutlet var tableview: UITableView!
var bioArray = NSArray(){
didSet{
dispatch_async(dispatch_get_main_queue()){
self.tableview.reloadData()
}}}
override func viewDidLoad()
{
super.viewDidLoad()
self.tableView.rowHeight = 80.0
// A switch Statement to check which cell was tapped and which API link to call
switch cellTapped
{
case 0:
test()
case 1:
test()
default:
test()
}
}
override func viewDidAppear(animated: Bool)
{
ViewControllerUtils().hideActivityIndicator(self.view)
}
func test() {
ViewControllerUtils().showActivityIndicator(self.view)
println("This is TWEST")
var request = NSMutableURLRequest(URL: NSURL(string: "APILink")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "GET"
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
var err: NSError?
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSArray
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
dispatch_async(dispatch_get_main_queue()) {
var alert = UIAlertController(title: "Alert", message: "Seems to be an error with server. Try Again Later", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}}
else {
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
//To to long tasks
// LoadingOverlay.shared.hideOverlayView()
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
//var newWeather = WeatherSummary(id:"")
if let parseJSON = json {
self.bioArray = parseJSON
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}}
})
task.resume()
}
func testTwo(){
println("THIS IS TEST 2")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return self.bioArray.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("bioCell", forIndexPath: indexPath) as! UITableViewCell
// Configure the cell...
let weatherSummary: AnyObject = bioArray[indexPath.row]
if let id = weatherSummary["employeeName"] as? String
{
cell.textLabel?.text = id
}
if let job = weatherSummary["sector"] as? String {
cell.detailTextLabel?.text = job
}
var fram = cell.imageView?.frame
//fram? = CGRectMake( 0, 0, 50, 55 )
let imageSize = 50 as CGFloat
fram?.size.height = imageSize
fram?.size.width = imageSize
cell.imageView!.frame = fram!
cell.imageView!.layer.cornerRadius = imageSize / 2.0
cell.imageView!.clipsToBounds = true
//cell.imageView?.image = UIImage(named: "userIcon.png")
if let userImage = weatherSummary["userImage"] as? String{
if let url = NSURL(string: userImage){
if let data = NSData(contentsOfURL: url){
if let image:UIImage = UIImage(data: data){
cell.imageView?.image = image
}
}
}
}
return cell
}
Try to dismiss on main queue and dissmiss it at the time you are getting response from server
dispatch_async(dispatch_get_main_queue(), {
ViewControllerUtils().hideActivityIndicator(self.view)
}))
You can use another custom activity indicator that I have got from somewhere. The simplest and effective one. (Though It has the text with the indicator, if you dont want text to be shown then you can customize it your way)
Make a class
class customActivityIndicator: UIVisualEffectView {
var text: String? {
didSet {
label.text = text
}
}
let activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.White)
let label: UILabel = UILabel()
let blurEffect = UIBlurEffect(style: .Dark)
let vibrancyView: UIVisualEffectView
init(text: String) {
self.text = text
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
super.init(effect: blurEffect)
self.setup()
}
required init(coder aDecoder: NSCoder) {
self.text = ""
self.vibrancyView = UIVisualEffectView(effect: UIVibrancyEffect(forBlurEffect: blurEffect))
super.init(coder: aDecoder)
self.setup()
}
func setup() {
contentView.addSubview(vibrancyView)
vibrancyView.contentView.addSubview(activityIndicator)
vibrancyView.contentView.addSubview(label)
activityIndicator.startAnimating()
}
override func didMoveToSuperview() {
super.didMoveToSuperview()
if let superview = self.superview {
let width: CGFloat = 150
let height: CGFloat = 50.0
self.frame = CGRectMake(superview.frame.size.width / 2 - width / 2,
superview.frame.height / 2 - height,
width,height)
vibrancyView.frame = self.bounds
let activityIndicatorSize: CGFloat = 40
activityIndicator.frame = CGRectMake(5, height / 2 - activityIndicatorSize / 2,
activityIndicatorSize,
activityIndicatorSize)
layer.cornerRadius = 8.0
layer.masksToBounds = true
label.text = text
label.textAlignment = NSTextAlignment.Center
label.frame = CGRectMake(activityIndicatorSize + 5, 0, width - activityIndicatorSize - 20, height)
label.textColor = UIColor.grayColor()
label.font = UIFont.boldSystemFontOfSize(16)
}
}
func show() {
self.hidden = false
}
func hide() {
self.hidden = true
}
}
To use this :
let spinner = customActivityIndicator(text: "Loading")
//To start animating
self.view.addSubview(spinner)
//To hide
self.spinner.hide()
This may help you.
Related
Currently, I am applying custom class SAFavoriteBtn to UIButton.
I wrote the code to get the API when the button was pressed within that class, I assigned the parameters to get the API data to the variables of UIViewController, I want to use the variable in SAFavoriteBtn. In this case, how should pass the value?
And this pattern is using segue?
UIViewController
class StoreViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate, UICollectionViewDelegateFlowLayout,UITableViewDelegate, UITableViewDataSource {
var store_id = ""
var instaId = ""
var store = [Store]()
var photoPath = [Store.photos]()
var tag = [Store.tags]()
var selectedImage : UIImage?
let defaultValues = UserDefaults.standard
#IBOutlet weak var imageCollectionView: UICollectionView!
#IBOutlet weak var mainImage: UIImageView!
#IBOutlet weak var nameLabel: UILabel!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var UIView: UIView!
#IBOutlet weak var tagCollectionView: UICollectionView!
#IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
//Collectiopn DetaSources
imageCollectionView.dataSource = self
imageCollectionView.delegate = self
tagCollectionView.dataSource = self
tagCollectionView.delegate = self
tableView.dataSource = self
tableView.delegate = self
//Navigation Color
self.navigationController!.navigationBar.setBackgroundImage(UIImage(), for: .default)
self.navigationController!.navigationBar.shadowImage = UIImage()
navigationController!.navigationBar.topItem!.title = ""
navigationController!.navigationBar.tintColor = UIColor.white
//UIView Shadow
let shadowPath = UIBezierPath(rect: UIView.bounds)
UIView.layer.masksToBounds = false
UIView.layer.shadowColor = UIColor.black.cgColor
UIView.layer.shadowOffset = .zero
UIView.layer.shadowOpacity = 0.2
UIView.layer.shadowPath = shadowPath.cgPath
//Request API
let url = URL(string: "http://example.com/store/api?store_id=" + store_id)
let request = URLRequest(url: url!)
let session = URLSession.shared
let encoder: JSONEncoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = .prettyPrinted
session.dataTask(with: request){(data, response, error)in if error == nil,
let data = data,
let response = response as? HTTPURLResponse{
let decoder: JSONDecoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
do {
let json = try decoder.decode(Store.self, from: data)
self.store = [json]
self.photoPath = json.photos
self.tag = json.tags
if let imageURL = URL(string: "http://example.com/photos/" + json.photos[0].path){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}else if let imageURL = URL(string: "http://example.com/photos/" + json.photos[0].path.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!){
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
DispatchQueue.main.async {
self.nameLabel.text = json.name
self.locationLabel.text = json.location
self.tableView.reloadData()
self.imageCollectionView.reloadData()
self.tagCollectionView.reloadData()
}
} catch {
print("error:", error.localizedDescription)
}
}
}.resume()
print(store)
//print(defaultValues.string(forKey: "id"))
// Image Collection view Layout
let itemSize = UIScreen.main.bounds.width/3.62 - 3.62
let layout = UICollectionViewFlowLayout()
layout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
layout.itemSize = CGSize(width: itemSize, height: itemSize)
layout.minimumInteritemSpacing = 1
layout.minimumLineSpacing = 1
imageCollectionView.collectionViewLayout = layout
// Tag Collection View
let tagLayout = UICollectionViewFlowLayout()
tagLayout.minimumLineSpacing = 1
tagLayout.minimumInteritemSpacing = 1
tagLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0)
tagLayout.itemSize = CGSize(width: 80, height: 24)
tagCollectionView.collectionViewLayout = tagLayout
//status bar color
self.setNeedsStatusBarAppearanceUpdate()
}
override var prefersStatusBarHidden: Bool {
return false
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return UIStatusBarStyle.lightContent
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// UI coner redius
let uiViewPath = UIBezierPath(roundedRect: UIView.bounds, byRoundingCorners: [.topLeft, .topRight], cornerRadii: CGSize(width: 8, height: 8))
let uiViewMask = CAShapeLayer()
uiViewMask.path = uiViewPath.cgPath
UIView.layer.mask = uiViewMask
navigationController!.navigationBar.topItem!.title = " "
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Collection
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if collectionView == self.imageCollectionView{
let imageCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)
let imageView = imageCell.contentView.viewWithTag(1) as! UIImageView
let textLabel = imageCell.contentView.viewWithTag(2) as! UILabel
let instaBtn = imageCell.contentView.viewWithTag(3) as! UIButton
instaBtn.tag = indexPath.row
if photoPath.count > indexPath.row{
if collectionView == self.imageCollectionView{
let url : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let imageURL = URL(string: url)
print(url)
if imageURL != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
imageCell.layer.masksToBounds = true;
imageCell.layer.cornerRadius = 3
imageView.image = image
textLabel.text = self.photoPath[indexPath.row].username
print(self.photoPath[indexPath.row].username)
}
}
}
}else{
let encodeURL : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let url = URL(string: encodeURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
imageCell.layer.masksToBounds = true;
imageCell.layer.cornerRadius = 3
imageView.image = image
textLabel.text = self.photoPath[indexPath.row].username
print(self.photoPath[indexPath.row].username)
}
}
}
}
}
}
instaBtn.addTarget(self, action: #selector(self.instaBtnTapped), for: UIControlEvents.touchUpInside)
imageCell.addSubview(instaBtn)
return imageCell
//Tag collection view
}else if collectionView == self.tagCollectionView{
let tagCell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "TagCell",for: indexPath)
let tagLabel = tagCell.contentView.viewWithTag(2) as! UILabel
if tag.count > indexPath.row{
tagLabel.text = tag[indexPath.row].name
}
tagCell.layer.cornerRadius = 12
return tagCell
}else{
return UICollectionViewCell()
}
}
//tapped instaBtn jump insta user page function
#objc func instaBtnTapped(sender: UIButton){
instaId = photoPath[sender.tag].username
let url = URL(string: "https://www.instagram.com/"+instaId+"/")
UIApplication.shared.open(url!, options: [ : ], completionHandler: nil)
print (sender.tag)
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView,
numberOfItemsInSection section: Int) -> Int {
return photoPath.count > 0 ? 3 : 0
}
func tagcollectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tag.count > 0 ? tag.count : 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return store.count > 0 ? 1 : 0
case 1 :
return store.count > 0 ? 1 : 0
case 2 :
return store.count > 0 ? 1 : 0
default:
return 0
}
}
//Collection view tap
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if collectionView == self.imageCollectionView{
let url : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let imageURL = URL(string: url)
print(url)
if imageURL != nil {
DispatchQueue.global().async {
let data = try? Data(contentsOf: imageURL!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}else{
let encodeURL : String = "http://example.com/photos/" + photoPath[indexPath.row].path
let url = URL(string: encodeURL.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!)
DispatchQueue.global().async {
let data = try? Data(contentsOf: url!)
if let data = data {
let image = UIImage(data: data)
DispatchQueue.main.async {
self.mainImage.image = image
}
}
}
}
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
switch indexPath.section {
case 0 :
//Price Cell
guard let priceCell = tableView.dequeueReusableCell(withIdentifier: "priceCell", for: indexPath) as? priceTableViewCell else { return UITableViewCell()}
if let price:String = store[indexPath.row].price{
priceCell.priceLabel.text! = price
}else{
priceCell.priceLabel.text! = "-"
}
return priceCell
case 1 :
//timeCell
guard let timeCell = tableView.dequeueReusableCell(withIdentifier: "timeCell", for: indexPath) as? timeTableViewCell else{return UITableViewCell()}
if let time:String = store[indexPath.row].open_time{
timeCell.timeLabel.text! = time
}else{
timeCell.timeLabel.text! = "-"
}
return timeCell
case 2 :
//closedayCell
guard let closedayCell = tableView.dequeueReusableCell(withIdentifier: "closedayCell", for: indexPath) as? closedayTableViewCell else { return UITableViewCell() }
if let closeday:String = store[indexPath.row].closed_day{
closedayCell.closedayLabel.text! = closeday
}else{
closedayCell.closedayLabel.text! = "-"
}
return closedayCell
default :
print("Default Selected")
}
return cell
}
#IBAction func moreImageBtn(_ sender: Any) {
let store_id = self.store_id
self.performSegue(withIdentifier: "toStorePhotoViewController", sender: store_id)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toStorePhotoViewController"{
let storePhotoViewController = segue.destination as! StorePhotoViewController
storePhotoViewController.store_id = sender as! String
}
}
//This is SAFavoriteBtn
//Bookmark Button
#IBAction func bookmarkBtn(_ sender: SAFavoriteBtn) {
}
#IBAction func locationBtn(_ sender: Any) {
let lat = store[0].lat
let lng = store[0].lng
if UIApplication.shared.canOpenURL(URL(string:"comgooglemaps://")!){
let urlStr : String = "comgooglemaps://?daddr=\(lat),\(lng)&directionsmode=walking&zoom=14"
UIApplication.shared.open(URL(string:urlStr)!,options: [:], completionHandler: nil)
}else{
let daddr = String(format: "%f,%f", lat, lng)
let urlString = "http://maps.apple.com/?daddr=\(daddr)&dirflg=w"
let encodeUrl = urlString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)!
let url = URL(string: encodeUrl)!
UIApplication.shared.open(url,options: [:], completionHandler: nil)
}
}
}
SAFavoriteBtn
import UIKit
class SAFavoriteBtn: UIButton {
var isOn = false
let defaultValues = UserDefaults.standard
//Want to use the variable of UIViewController with UIButton custom class in this part
var storeId = ""
override init(frame: CGRect) {
super.init(frame:frame)
initButton()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initButton()
}
func initButton() {
setImage(UIImage(named:"bookmark.png"), for: UIControlState.normal)
addTarget(self, action: #selector(SAFavoriteBtn.buttonPressed), for: .touchUpInside)
}
#objc func buttonPressed() {
activateBtn(bool: !isOn)
}
func activateBtn(bool : Bool){
isOn = bool
//UI
let image = bool ? "bookmark_after.png" : "bookmark.png"
setImage(UIImage(named: image), for: UIControlState.normal)
//API
bool ? favorite() : deleteFavorite()
}
func favorite(){
let user_id = defaultValues.string(forKey: "userId")
let url = URL(string: "http://example.com/api/store/favorite?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postParameters = "user_id=" + user_id! + "&store_id=" + storeId
request.httpBody = postParameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
print("favorite")
}
func deleteFavorite(){
let user_id = defaultValues.string(forKey: "userId")
let url = URL(string: "http://example.com/api/store/favorite?")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postParameters = "user_id=" + user_id! + "&store_id=" + storeId
request.httpBody = postParameters.data(using: .utf8)
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if error == nil, let data = data, let response = response as? HTTPURLResponse {
print("Content-Type: \(response.allHeaderFields["Content-Type"] ?? "")")
print("statusCode: \(response.statusCode)")
print(String(data: data, encoding: .utf8) ?? "")
}
}.resume()
print("delete")
}
}
I am new to Swift programming
SearchBar controller with tableview. I want display the multiple students in table view its working fine. I can add the search bar controller to table view and display the particular students data. table view cell contains the student information and image I want display particular student after search
this is the code
#IBOutlet var SearchBarDisp:UISearchBar!
override func viewDidLoad()
{
super.viewDidLoad()
searchController.searchResultsUpdater = self
searchController.hidesNavigationBarDuringPresentation = false
searchController.dimsBackgroundDuringPresentation = false
tableView.tableHeaderView = searchController.searchBar
}
func updateSearchResults(for searchController: UISearchController) {
//todo
}
I can get student data from json
func getKids(url : String) {
UIApplication.shared.beginIgnoringInteractionEvents()
var errorCode = "1"
var msg = "Failed"
var request = URLRequest(url: URL(string: "getstaffstudents",
relativeTo: URL(string: serverURL+"/rkapi/api/"))!)
let session = URLSession.shared
request.httpMethod = "POST"
let bodyData = "staffId=\(staffId)"
request.httpBody = bodyData.data(using: String.Encoding.utf8);
let task = session.dataTask(with:request,completionHandler:{(d,response,error)in
do{
if let data = d {
if let jsonData = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
errorCode = String(describing: jsonData["errorCode"]!)
msg = jsonData["msg"] as! String
print("msg values",msg)
if errorCode == "0" {
if let kid_list = jsonData["students"] as? NSArray {
for i in 0 ..< kid_list.count {
if let kid = kid_list[i] as? NSDictionary {
kidHoleData.removeAll()
let imageURL = url+"/images/" + String(describing: kid["photo"]!)
self.kidsData.append(Kids(
studentId: kid["studentId"] as? String,
name:kid["name"] as? String,
classId : kid["classId"] as? String,
standard: ((kid["standard"] as? String)! + " " + (kid["section"] as? String)!),
photo : (imageURL),
school: kid["schoolName"] as? String,
schoolId : "1",
url : url)
)
}
}
self.loopCount += 1
self.do_table_refresh()
}
} else {
self.displayAlert("Kids", message: msg)
}
} else {
self.displayAlert("Kids", message: "Data Not Available. Please try again")
}
}else {
self.displayAlert("Kids", message: "Please try again")
}
} catch let err as NSError {
print("JSON Error \(err)")
}
})
task.resume()
}
Table view
func numberOfSections(in tableView: UITableView) -> Int {
return (kidsData.count == 0) ? 0 : 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return kidsData.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(
withIdentifier: "Kidscell", for: indexPath) as! KidsTableViewCell
let maskLayer = CAShapeLayer()
let bounds = cell.bounds
maskLayer.path = UIBezierPath(roundedRect: CGRect(x: 3, y: 3, width: bounds.width-15, height: bounds.height-15), cornerRadius: 2).cgPath
cell.layer.mask = maskLayer
let row = (indexPath as NSIndexPath).row
if(kidsData.count>0){
let kid = kidsData\[row\] as Kids
cell.kidNameLabel.text = kid.name
cell.classLabel.text = kid.standard
cell.kidNameLabel.lineBreakMode = .byWordWrapping
cell.kidNameLabel.numberOfLines = 0
cell.kidImageView.image = UIImage(named: "profile_pic")
cell.kidImageView.downloadImageFrom(link: kid.photo!, contentMode: UIViewContentMode.scaleAspectFit) //set your image from link array.
}
return cell
}
I want display particular student in table view(like if I can search student name as vani it's display the student vani in table view) pls help me
copy the hole data in to the attendanceInfoDupilicate
var attendanceInfoDupilicate = [AttendanceInfo]()
Inside of the Json service call at end
self.attendanceInfoDupilicate = self.attendanceInfo
updater the search controller
func updateSearchResults(for searchController: UISearchController)
{
let searchToSeatch = AttendanceSearchBarController.searchBar.text
if(searchToSeatch == "")
{
self.attendanceInfo = self.attendanceInfoDupilicate
}
else{
self.attendanceInfo.removeAll()
let AttedanceData = self.attendanceInfoDupilicate
var kidsArray = [String]()
for AttendanceInfo in AttedanceData
{
kidsArray.append(AttendanceInfo.name)
if(AttendanceInfo.name.range(of: searchToSeatch!, options: .caseInsensitive) != nil)
{
self.attendanceInfo.append(AttendanceInfo)
}
}
}
self.TableView.reloadData()
}
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.
I try to update my tableview after my REST-call is finished and all entities are stored in CoreData. I tried dispatch_asynch but the tableview doesn't reload when expected. I am using a UIRefreshControl to trigger refreshing. Usually, the correct tableview data is displayed after 2 refreshes. I have no idea why.
I can confirm that my tableview instance IS NOT nil.
#IBAction func refreshTriggered(sender: UIRefreshControl) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.evMan.retrieveAndSaveEvents(self.pubMan.getAllPublishers())
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
}
This is my retrieveAndSaveEvents method from my 'EventManager' evMan:
func retrieveAndSaveEvents(forPublishers: [PUBLISHERS]) {
for publisher in forPublishers {
let pubId = publisher.id as Int
let str = "/publishers/\(pubId)/events"
// resty is an instance of my REST-api wrapper
self.resty.GET(self.server, route: str, onCompletion: {json in
let result = json.asArray
for var i = 0; i < result!.count; i++ {
if !self.isIDAlreadyInDB(json[i]["id"].asInt!) {
let newEv = NSEntityDescription.insertNewObjectForEntityForName("EVENTS", inManagedObjectContext: self.context!) as! EVENTS
newEv.headline = json[i]["headline"].asString!
newEv.id = json[i]["id"].asInt!
newEv.content = json[i]["content"].asString!
newEv.ofPublisher = publisher
do {
try self.context!.save()
} catch _ {
}
print("New Event from \(publisher.name): \(newEv.headline)")
}
}
})
}
}
FYI, here's my cellForRowAtIndexPath: (I am using a Custom UITableViewCell)
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("eventCell") as? EventCell
let curEv = evMan.getEvents()[indexPath.row]
cell?.infoLabel.text = curEv.ofPublisher?.name
cell?.myImageView.image = UIImage(named: "icon.png")
cell?.detailLabel.text = curEv.headline
cell?.timeLabel.attributedText = NSAttributedString(string: self.dateFormatter.stringFromDate(curEv.updatedAt))
cell?.contentView.backgroundColor = UIColor.clearColor()
cell?.backgroundColor = UIColor(white: 1.0, alpha: 0.5)
return cell!
}
Here is my REST-wrapper:
class REST: NSObject {
// Basic Auth
let sConfig = ServerConfig()
var username = "rest"
var password = "resttest"
override init() {
username = sConfig.getUserLogin().user
password = sConfig.getUserLogin().pass
}
func GET(server: String, route: String, onCompletion: (JSON) -> Void) {
let route = server+route
makeHTTPGetRequest(route, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func makeHTTPGetRequest(path: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
let loginString = NSString(format: "%#:%#", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
let loginvalue = "Basic " + base64LoginString
// add Headers
request.addValue(loginvalue, forHTTPHeaderField: "Authorization")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
let json:JSON = JSON(data: data!)
onCompletion(json, error)
})
task.resume()
}
}
#IBAction func refreshTriggered(sender: UIRefreshControl) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.evMan.retrieveAndSaveEvents(self.pubMan.getAllPublishers())
})
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
}
Now, you cannot guarantee reloadData() happens after self.evMan.retrieveAndSaveEvents(self.pubMan.getAllPublishers()) , because they are not happen in the same queue. And probably, reloadData() happens before retrieve.
Option 1:
You should put the block :
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
at the end of func retrieveAndSaveEvents(self.pubMan.getAllPublishers())
Option 2 :
#IBAction func refreshTriggered(sender: UIRefreshControl) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.evMan.retrieveAndSaveEvents(self.pubMan.getAllPublishers())
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
})
}
EDIT:
I did not see there is another queue in retrieveAndSaveEvents
So, put the
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
}
at the end of:
self.resty.GET(self.server, route: str, onCompletion: {json in
let result = json.asArray
for var i = 0; i < result!.count; i++ {
if !self.isIDAlreadyInDB(json[i]["id"].asInt!) {
let newEv = NSEntityDescription.insertNewObjectForEntityForName("EVENTS", inManagedObjectContext: self.context!) as! EVENTS
newEv.headline = json[i]["headline"].asString!
newEv.id = json[i]["id"].asInt!
newEv.content = json[i]["content"].asString!
newEv.ofPublisher = publisher
do {
try self.context!.save()
} catch _ {
}
print("New Event from \(publisher.name): \(newEv.headline)")
}
}
})
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)
}
}