UIPageViewController with transition style Scroll autoplay wrong video - ios

I have a 2 dimensional UIPageViewController (Two PageViewController, one horizontal, and one vertical).
On the first level (X = 0), I display full screen videos with autoplay. When i'm using transition style Page Curl, i have no problems, but with transition style Scroll, the fact that the "after view controller" is preloaded, it will execute the code and autoplay the video (hosted on youtube) before, therefore, it will stop the video which on the view controller i'm actually seeing, and also, i will hear that video in the background.
I can't figure how to make sure that the video that is playing is one i'm really looking at.
this is how I set my view:
import UIKit
class YViewController: UIViewController {
var yPageIndex: Int!
var xPageIndex: Int!
var yLabelText: String!
override func viewDidLoad() {
super.viewDidLoad()
if (xPageIndex == 0) { // if xPageIndex == 0 then you are on the tag page. Else, you are browsing
// HOME SCREEN
let homeLabel = UILabel(frame: CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height))
// homeLabel.backgroundColor = UIColor.blueColor()
// homeLabel.center = CGPointMake(self.view.frame.size.width / 2, self.view.frame.size.height / 2)
// homeLabel.textAlignment = NSTextAlignment.Center
homeLabel.numberOfLines = 0
let htmlString = "<center><h1>Welcome John Smith</h1> <h2> Your Tags: </h2> <i> #unity #iOS #php #XCODE</i><br><br><br><br><br><br> <i>Swipe left to start browsing job offers</i></center>"
let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
homeLabel.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
self.view.addSubview(homeLabel)
} else {
if yPageIndex == 0 { // if yPageIndex == 0 then you are on video page. Else, you are on the job description page
var webView = UIWebView(frame: self.view.frame)
view.addSubview(webView)
view.bringSubviewToFront(webView)
webView.allowsInlineMediaPlayback = true
webView.mediaPlaybackRequiresUserAction = false
webView.scrollView.bounces = false
let videoID = mainInstance.jobInfoArray[xPageIndex].videoId
let embededHTML = "<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)' src='http://www.youtube.com/embed/\(videoID)?enablejsapi=1&rel=0&playsinline=1&autoplay=0&controls=0' frameborder='0'></body></html>"
webView.loadHTMLString(embededHTML, baseURL: NSBundle.mainBundle().resourceURL)
print("width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)'")
} else {
print("Job " + mainInstance.jobInfoArray[xPageIndex].jobTitle)
print("width='\(self.view.frame.size.width)' height='\(self.view.frame.size.height)'")
var homeLabel = UILabel(frame: CGRectMake(0, 30, self.view.frame.size.width, self.view.frame.size.height))
homeLabel.numberOfLines = 0
let htmlString = "<h1>\(mainInstance.jobInfoArray[xPageIndex].jobTitle)</h1> <h2>Company: \(mainInstance.jobInfoArray[xPageIndex].jobCompany) </h2> <i> tags: \(mainInstance.jobInfoArray[xPageIndex].jobKeyWords)</i><br>Salary: \(mainInstance.jobInfoArray[xPageIndex].jobSalary)<br> <br> \(mainInstance.jobInfoArray[xPageIndex].jobDescription)"
let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let attributedOptions = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
homeLabel.attributedText = attributedString
} catch _ {
print("Cannot create attributed String")
}
homeLabel.sizeToFit()
self.view.addSubview(homeLabel)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
and this how I configured my UIPageView
class XViewController: UIViewController, UIPageViewControllerDataSource {
// to init y display
var yPageViewController: UIPageViewController!
var yLabel: NSArray!
// To remove ?
var xPageIndex: Int!
var videoTitleText: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// self.videoLabel.text = self.videoTitleText
self.yLabel = NSArray(objects: "Video", "Job Description")
self.yPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("yPageViewController") as! UIPageViewController
self.yPageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(0) as YViewController
let viewControllers = NSArray(object: startVC)
self.yPageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: false, completion: nil)
self.yPageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width , self.view.frame.size.height)
self.addChildViewController(self.yPageViewController)
self.view.addSubview(self.yPageViewController.view)
self.yPageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(yIndex: Int) -> YViewController
{
if ( (self.yLabel.count == 0) || (yIndex >= self.yLabel.count) ) {
return YViewController()
}
let vc: YViewController = self.storyboard?.instantiateViewControllerWithIdentifier("yContentViewController") as! YViewController
vc.yPageIndex = yIndex
vc.xPageIndex = xPageIndex
vc.yLabelText = self.yLabel[yIndex] as! String
return vc
}
// MARK: Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! YViewController
var yIndex = vc.yPageIndex as Int
if ( (yIndex == 0) || (yIndex == NSNotFound) ) {
return nil
}
yIndex--
return self.viewControllerAtIndex(yIndex)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! YViewController
var yIndex = vc.yPageIndex as Int
if (yIndex == NSNotFound || xPageIndex == 0) {
return nil
}
yIndex++
if (yIndex == self.yLabel.count)
{
return nil
}
return self.viewControllerAtIndex(yIndex)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
and just in case, here the ViewConytoller (the fact that it goes horizontal and vertical might makes it a bit hard to figure out.
import UIKit
class ViewController: UIViewController, UIPageViewControllerDataSource {
var xPageViewController: UIPageViewController!
var videoId: NSArray!
// var yPageViewController: UIPageViewController!
// var jobId: NSArray!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.videoId = NSArray(objects: "Video #1", "Video #2", "Video #3", "Video #4", "Video #5")
self.xPageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("xPageViewController") as! UIPageViewController
self.xPageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(0) as XViewController
let viewControllers = NSArray(object: startVC)
self.xPageViewController.setViewControllers(viewControllers as! [UIViewController], direction: .Forward, animated: false, completion: nil)
self.xPageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width , self.view.frame.size.height)
self.addChildViewController(self.xPageViewController)
self.view.addSubview(self.xPageViewController.view)
self.xPageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(xIndex: Int) -> XViewController
{
if ( (self.videoId.count == 0) || (xIndex >= self.videoId.count) ) {
return XViewController()
}
let vc: XViewController = self.storyboard?.instantiateViewControllerWithIdentifier("xContentViewController") as! XViewController
vc.xPageIndex = xIndex
vc.videoTitleText = self.videoId[xIndex] as! String
return vc
}
// MARK: Page View Controller Data Source
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! XViewController
var xIndex = vc.xPageIndex as Int
if ( (xIndex == 0) || (xIndex == NSNotFound) ) {
return nil
}
xIndex--
return self.viewControllerAtIndex(xIndex)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
let vc = viewController as! XViewController
var xIndex = vc.xPageIndex as Int
if (xIndex == NSNotFound) {
return nil
}
xIndex++
if (xIndex == self.videoId.count)
{
return nil
}
return self.viewControllerAtIndex(xIndex)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
I'm new to this, so i'm sorry if i'm not clear or if I'm not following the "posting rules" for this site.
If anyone as any ideas on how i could achieve that, that would be brilliant.
Thanks a lot,
Julien

Related

Table View is empty when I switch Tab Bar controller screens

I have a Tab bar Controller to manage all the views. The problem I'm having is when I call a function in searchViewController (doAThing()) from HomeViewController which reloads the tableView in searchViewController, the tableView is empty when the Tab bar controller switches views.
Why does calling the doAThing method in my searchViewController not refresh my tableView?
How can I fill my tableView with values.
HomeViewController.swift
import UIKit
class HomeViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UISearchBarDelegate{
#IBOutlet weak var productCollectionView: UICollectionView!
#IBOutlet weak var storesCollectionView: UICollectionView!
#IBOutlet var searchQ: UISearchBar!
#IBOutlet weak var scrollView: UIScrollView!
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if(collectionView == storesCollectionView) {
return storesImages.count
}
return productsImages.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if(collectionView == storesCollectionView) {
let cell2 = storesCollectionView.dequeueReusableCell(withReuseIdentifier: "storesCell", for: indexPath) as! StoreCollectionViewCell
cell2.compstoreImage.image = UIImage(named: storesImages[indexPath.row])
return cell2
}
else{
let cell = productCollectionView.dequeueReusableCell(withReuseIdentifier: "productsCell", for: indexPath) as! ProductCollectionViewCell
cell.pillImage.image = UIImage(named: productsImages[indexPath.row])
return cell
}
}
var productsImages:[String] = ["pcPic", "picturePC"]
var storesImages:[String] = ["newarkStore", "compeStore"]
override func viewDidLoad() {
super.viewDidLoad()
searchQ.delegate = self
scrollView.contentSize = CGSize(width: self.view.frame.width, height: self.view.frame.height)
// searchQ.delegate = self
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//self.tabBarController?.tabBar.isHidden = false
}
func searchBarSearchButtonClicked(_ searchQ: UISearchBar)
{
print("*********")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let resultViewController = storyBoard.instantiateViewController(withIdentifier: "SearchViewController") as! searchViewController
// resultViewController.searchQuery = searchQ
resultViewController.doAthing(searchQ)
self.tabBarController?.selectedIndex = 3
// NotificationCenter.default.post(name: NSNotification.Name(rawValue: "load"), object: nil)
resultViewController.resultsView.reloadData()
}
// func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//
// print("*********")
//
// let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "SearchViewController") as! searchViewController
// secondViewController.doAthing(searchBar)
// self.navigationController!.pushViewController(secondViewController, animated: true)
//
//
//
// //let titles: Elements = try doc.select("a[product-thumb]")
// //let titles: String = try doc.select("a").attr("product-thumb")
//
// // print(titles
//
// hideKeyboardWhenTappedAround()
//
// }
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
searchViewController.swift
import UIKit
import SwiftSoup
class searchViewController: UIViewController{
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var resultsView: UITableView!
#IBOutlet var searchQuery: UISearchBar!
// let content = try! String(contentsOf: URL(string: "https://www.locally.com/search/all/activities/depts?q=bottle")!)
// let doc: Document = try! SwiftSoup.parse(content)
var products: [String] = []
//let products = ["Computer", "PC", "Laptop"]
let stores = ["Computer Central", "Fry's Electronics", "Best Buy"]
//var stores: [String] = []
let into = ["Custom PC with high performanc. Perfect for gaming and streaming. Great condition", "Custom PC with high performanc. Perfect for gaming and streaming. Great condition", "Custom PC with high performanc. Perfect for gaming and streaming. Great condition"]
var dollars: [String] = []
//let dollars = [100, 220, 129, 100, 220, 129]
let likes = [10, 24, 24, 24 , 456, 46, 46]
//let miles = ["3.2 mi", "4.1 mi", "6.3 mi", "3.2 mi", "4.1 mi", "6.3 mi"]
var miles: [String] = []
// let names = ["Central Computers", "CompE", "geekStore", "Central Computers", "CompE", "geekStore"]
var names: [String] = []
let numbers = ["510-329-0172", "510-456-7345", "510-329-0172", "510-329-0172", "510-456-7345", "510-329-0172"]
var images: [UIImage] = []
var categories: [String] = []
var descriptions: [String] = []
var stars: [String] = []
var ratings: [Double] = []
var ratingImage: [[UIImage]] = [[]]
var phones: [String] = []
var cities: [String] = []
//var webCounter:Int = 0
var x:Double = 0
var y:Int = 0
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(loadList), name: NSNotification.Name(rawValue: "load"), object: nil)
searchQuery.delegate = self
resultsView.delegate = self
resultsView.dataSource = self
//set the height of each row in tableview
self.resultsView.rowHeight = 200.0
// Do any additional setup after loading the view.
}
#objc func loadList(notification: NSNotification) {
//load data here
self.resultsView.reloadData()
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//searchBar.inputViewController?.dismissKeyboard()
searchBar.inputViewController?.dismiss(animated: true)
doAthing(searchBar)
self.searchQuery.endEditing(true)
self.resultsView.keyboardDismissMode = .onDrag
hideKeyboardWhenTappedAround()
}
func doAthing(_ searchBar: UISearchBar) {
do {
let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
loadingIndicator.hidesWhenStopped = true
loadingIndicator.style = UIActivityIndicatorView.Style.medium
loadingIndicator.startAnimating();
alert.view.addSubview(loadingIndicator)
present(alert, animated: true, completion: nil)
print("reached here")
let html = try String(contentsOf: URL(string: "https://www.locally.com/search/all/activities/depts?q=" + searchBar.text!)!)
//let doc: Document = try SwiftSoup.parse(html)
guard let titles: Elements = try? SwiftSoup.parse(html).getElementsByClass("product-thumb ") else {return}//select("a") else {return}
guard let prices: Elements = try? SwiftSoup.parse(html).getElementsByClass("product-thumb-price dl-price") else {return}
guard let Stores: Elements = try? SwiftSoup.parse(html).getElementsByClass("filter-label-link") else {return}
guard let Images: Elements = try? SwiftSoup.parse(html).getElementsByClass("product-thumb-img") else {return}
products = []
miles = []
dollars = []
names = []
images = []
stars = []
for title: Element in titles.array() {
print("title" + String(titles.size()))
products.append(try! title.attr("data-product-name"))
guard let url: URL = try? URL(string: "https://www.locally.com/" + String(try! title.attr("href")))
else
{
miles.append("-")
continue
}
let html1 = try String(contentsOf: url)
guard let distances: Element = try? SwiftSoup.parse(html1).getElementsByClass("conv-section-distance dl-store-distance").first()
else
{
miles.append("-")
continue
}
print(try! distances.ownText())
miles.append(try! distances.ownText())
guard let K: Array<String> = try? SwiftSoup.parse(html1).getElementsByClass("breadcrumbs container").eachText() else {return}
let str = (try! K.last!.components(separatedBy: "/") )
categories.append(str[str.count - 2])
print(str[str.count - 2])
guard let desc: Array<String> = try? SwiftSoup.parse(html1).getElementsByClass("pdp-information").eachText() else {return}
guard let s:String = try? desc[1]
else {
return
}
descriptions.append( String( s.suffix(s.count - 19) ) )
print( String( s.suffix(s.count - 19) ) )
guard let star: Element = try? SwiftSoup.parse(html1).getElementsByClass("stars").first()
else
{
print("no reviews")
ratings.append(0)
continue
}
print(try! star.attr("data-rating"))
//ratings.append(try! star.attr("data-rating")) ?? ()
let x = Double(try! star.attr("data-rating")) ?? 0
print("y: " + String(Int(x)))
ratings.append(x)
guard let locations: Element = try? SwiftSoup.parse(html1).getElementsByClass("conv-section-store-address section-subtitle dl-store-address js-store-location").first()
else
{
print("cant find city")
return
}
let string = locations.ownText()
print("location: " + String(string.prefix(string.count - 10)) )
cities.append(try! String(string.prefix(string.count - 10)))
guard let phoneNums: Element = try? SwiftSoup.parse(html1).getElementsByClass("selected-retailer-info-link btn-action-sm tooltip").first()
else
{
print("link not found")
return
}
guard let urls:URL = try? URL(string: "https://www.locally.com/" + phoneNums.attr("href") )
else
{
return
}
let html2 = try String(contentsOf: urls )
guard let storePage:Element = try? SwiftSoup.parse(html2).getElementsByClass("landing-page-phone-label").first() else {
print("Phone Number not found")
return
}
let sp = try? storePage.ownText
if let s = sp {
phones.append(try! s())
}
else {
phones.append("N/A")
}
print(try! storePage.ownText())
//
// let html1 = try String(contentsOf: url)
}
for price: Element in prices.array() {
print("prices" + String(prices.size()))
print(String(try! price.ownText()))
dollars.append(try! price.ownText())
}
for store: Element in Stores.array() {
print("Stores" + String(Stores.size()))
names.append(try! store.ownText()) ?? names.append("N/A")
}
for image: Element in Images.array() {
guard let url = URL(string: try! image.attr("src") ) else { return }
let data = try? Data(contentsOf: url)
if let imageData = data {
images.append( UIImage(data: imageData)! )
}
else {
images.append(UIImage(named: "pcPic")!)
}
//images.append(try! image.downloaded(from: image.attr("src")))
}
dismiss(animated: false, completion: nil)
resultsView.reloadData()
//let titles: Elements = try doc.select("a[product-thumb]")
//let titles: String = try doc.select("a").attr("product-thumb")
// print(titles)
} catch Exception.Error(type: let type, Message: let message) {
print(type)
print(message)
} catch {
print("")
}
}
// override func viewWillAppear(_ animated: Bool) {
// super.viewWillAppear(animated)
// self.tabBarController?.tabBar.isHidden = false
// }
//When user changes segment, tableview is reloaded
#IBAction func segmentChanged(_ sender: Any) {
resultsView.reloadData();
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
func imageWithImage(image: UIImage, scaledToSize newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContext(newSize)
image.draw(in: CGRect(x: 0 ,y: 20 ,width: newSize.width ,height: newSize.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!.withRenderingMode(.alwaysOriginal)
}
}
extension searchViewController: UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("reached here")
switch segmentedControl.selectedSegmentIndex {
case 0:
return products.count
case 1:
return stores.count
case 2:
return (products.count + stores.count)
default:
break
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "resultsTableViewCell") as! resultsTableViewCell
switch segmentedControl.selectedSegmentIndex {
case 0:
cell.titleLabel?.text = products[indexPath.row]
cell.productImage?.image = images[indexPath.row]
// cell.descriptionLabel?.text = into[indexPath.row]
// cell.descriptionLabel?.numberOfLines = 0
cell.price?.text = String(dollars[indexPath.row])
cell.distance?.text = miles[indexPath.row]
cell.storeName?.numberOfLines = 0
cell.storeName?.text = names[indexPath.row]
cell.phoneNumber?.text = phones[indexPath.row]
let ratNumber = ratings[indexPath.row]
if( ratNumber == 0 )
{
cell.rating?.text = "No Reviews"
}
else
{
cell.rating?.text = String(ratNumber)
}
if(ratNumber > 4.5)
{
cell.star1.image = UIImage(named: "regular_5")
}
else if(ratNumber > 4.0)
{
cell.star1.image = UIImage(named: "regular_4_half")
}
else if(ratNumber == 4.0)
{
cell.star1.image = UIImage(named: "regular_4")
}
else if(ratNumber > 3.0)
{
cell.star1.image = UIImage(named: "regular_3_half")
}
else if(ratNumber == 3.0)
{
cell.star1.image = UIImage(named: "regular_3")
}
else if(ratNumber > 2.0)
{
cell.star1.image = UIImage(named: "regular_2_half")
}
else if(ratNumber == 2.0)
{
cell.star1.image = UIImage(named: "regular_2")
}
else if(ratNumber > 1.0)
{
cell.star1.image = UIImage(named: "regular_1_half")
}
else if(ratNumber == 1.0)
{
cell.star1.image = UIImage(named: "regular_1")
}
else
{
cell.star1.image = UIImage(named: "regular_0")
}
cell.rating?.numberOfLines = 0
// cell.phoneNumber?.text = numbers[indexPath.row]
case 1:
cell.titleLabel?.text = stores[indexPath.row]
cell.productImage?.image = imageWithImage(image: UIImage.init(named: "pcPic")!, scaledToSize: CGSize(width: 400, height: 300))
// cell.descriptionLabel?.text = into[indexPath.row]
// cell.descriptionLabel?.numberOfLines = 0
cell.price?.text = String(dollars[indexPath.row])
cell.distance?.text = miles[indexPath.row]
cell.storeName?.text = names[indexPath.row]
cell.phoneNumber?.text = numbers[indexPath.row]
case 2:
var all = products + stores
all.shuffle()
let alls = into + into
cell.titleLabel?.text = all[indexPath.row]
cell.productImage?.image = imageWithImage(image: UIImage.init(named: "pcPic")!, scaledToSize: CGSize(width: 400, height: 300))
// cell.descriptionLabel?.text = alls[indexPath.row]
// cell.descriptionLabel?.numberOfLines = 0
cell.price?.text = String(dollars[indexPath.row])
cell.distance?.text = miles[indexPath.row]
cell.storeName?.text = names[indexPath.row]
cell.phoneNumber?.text = numbers[indexPath.row]
default:
break
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// let vc = self.storyboard?.instantiateViewController(withIdentifier: "ShopViewController") as! ShopViewController
// self.present(vc, animated: true, completion: nil)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let destinationVC = storyboard.instantiateViewController(withIdentifier: "ProductViewController") as! ProductViewController
destinationVC.ktitle = products[indexPath.row]
destinationVC.kprice = dollars[indexPath.row]
// destinationVC.kdescription = [indexPath.row]
destinationVC.kimage = images[indexPath.row]
// destinationVC.klikes = likes[indexPath.row]
destinationVC.kcategory = categories[indexPath.row]
destinationVC.kdescription = descriptions[indexPath.row]
destinationVC.kname = names[indexPath.row]
destinationVC.kmiles = miles[indexPath.row]
destinationVC.klocation = cities[indexPath.row]
self.present(destinationVC, animated: true, completion: nil)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard(_:)))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
#objc func dismissKeyboard(_ sender: UITapGestureRecognizer) {
view.endEditing(true)
if let nav = self.navigationController {
nav.view.endEditing(true)
}
}
}
First, it's probably not a good idea to switch to a different tab in that manner. Users understand that tapping a tab-bar icon/button takes them to a new tab. If you're jumping around in the tabs via code, it can be very confusing for the user.
But... it's your app.
The reason your code does not "refresh my tableView" is because you never actually reference that view controller.
In your code:
func searchBarSearchButtonClicked(_ searchQ: UISearchBar)
{
print("*********")
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
// here you create a NEW instance of searchViewController
let resultViewController = storyBoard.instantiateViewController(withIdentifier: "SearchViewController") as! searchViewController
// you call a func in that instance
resultViewController.doAthing(searchQ)
// you switch to tab index 3, which holds an OLD instance of searchViewController
self.tabBarController?.selectedIndex = 3
// you tell resultsView in the NEW instance to reloadData()
resultViewController.resultsView.reloadData()
// as soon as you exit this func, the NEW instance is deleted
}
You could do something like this:
func searchBarSearchButtonClicked(_ searchQ: UISearchBar)
print("*********")
// get a reference to the searchViewController that is already
// part of the tab bar controller
if let tb = self.tabBarController,
let controllers = tb.viewControllers,
let resultVC = controllers[3] as? searchViewController {
// call the func
resultVC.doAthing("new")
tb.selectedIndex = 3
}
}
However, that's really not a great approach... Just for one example, Suppose you change the order of the tabs at some point?
You're better off using either a custom tab bar controller class, or using a "data manager" class.
I'd suggest you head over to google (or your favorite search engine) and search for swift pass data between tab bar view controllers -- you'll find plenty of discussions, articles, examples, etc.
Edit -- comment
In HomeViewController replace your func searchBarSearchButtonClicked with this:
func searchBarSearchButtonClicked(_ searchQ: UISearchBar)
{
print("1 - searchBarSearchButtonClicked")
guard let btnTitle = searchQ.largeContentTitle else {
print("2 - FAILED to get searchQ.largeContentTitle")
return
}
print("2 - got btnTitle", btnTitle)
if let tb = self.tabBarController {
print("3 - got a tab bar controller reference")
if let controllers = tb.viewControllers {
print("4 - got controllers reference")
if controllers.count == 4 {
print("5 - we have 4 controllers")
if let resultVC = controllers[3] as? searchViewController {
print("6 - got a reference to searchViewController")
// if we have not yet selected the 4th tab,
// the view will not yet have been loaded
// so make sure it is
resultVC.loadViewIfNeeded()
// call the func, passing the button title
resultVC.doAthing(searchQ)
// switch to the 4th tab
tb.selectedIndex = 3
print("7 - we should now be at searchViewController")
} else {
print("6 - FAILED TO GET a reference to searchViewController")
}
} else {
print("5 - FAILED TO GET a reference to searchViewController")
}
} else {
print("4 - FAILED TO GET a reference to searchViewController")
}
} else {
print("3 - FAILED TO GET a reference to searchViewController")
}
}
Then see what messages get printed to the debug console.

How can I change the images size on PageViewController in Swift 3?

When I first faced this problem on other ViewController, I solved it by setting constraint constants.
But, on the PageViewController, I cannot solve this problem.
These are codes about PageViewController.
I have 2 swift files related to PageViewController and there is only one ViewController on Main.storyboard to show page-based screen and it's linked to FirstPageViewController.swift
FirstPageViewController.swift
import UIKit
class FirstPageViewController: UIViewController, UIPageViewControllerDataSource {
var pageViewController : UIPageViewController?
var pageTitles : Array<String> = ["", "", "", "", "", "", "", "", "", "", "", ""]
// pageTitles 배열의 수를 기준으로 페이지가 생성 되므로 원하는 페이지만큼 ""를 입력해야 함.
var pageImages : Array<String> = ["S1_01.jpg", "S1_02.jpg", "S1_03.jpg", "S1_04.jpg", "S1_05.jpg", "S1_06.jpg", "S1_07.jpg", "S1_08.jpg", "S1_09.jpg", "S1_10.jpg", "S1_11.jpg", "S1_12.jpg"] // 그림자극장 page에 들어갈 이미지 파일들
var currentIndex : Int = 0
override func viewDidLoad() {
super.viewDidLoad()
showSecondAlert()
showFirstAlert()
pageViewController = UIPageViewController(transitionStyle: .pageCurl, navigationOrientation: .horizontal, options: nil)
pageViewController!.dataSource = self // (transitionStyle: 페이지 넘김 형식, navigationOrientation: 페이지 방향, options: nil)
let startingViewController: FirstDataViewController = viewControllerAtIndex(index: 0)!
let viewControllers = [startingViewController]
pageViewController!.setViewControllers(viewControllers , direction: .forward, animated: false, completion: nil)
pageViewController!.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height);
addChildViewController(pageViewController!)
view.addSubview(pageViewController!.view)
pageViewController!.didMove(toParentViewController: self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
var index = (viewController as! FirstDataViewController).pageIndex
if (index == 0) || (index == NSNotFound) {
return nil
}
index -= 1
return viewControllerAtIndex(index: index)
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
var index = (viewController as! FirstDataViewController).pageIndex
if index == NSNotFound {
return nil
}
index += 1
if (index == self.pageTitles.count) {
return nil
}
return viewControllerAtIndex(index: index)
}
func viewControllerAtIndex(index: Int) -> FirstDataViewController? {
if self.pageTitles.count == 0 || index >= self.pageTitles.count {
return nil
}
let pageContentViewController = FirstDataViewController()
pageContentViewController.imageFile = pageImages[index]
pageContentViewController.titleText = pageTitles[index]
pageContentViewController.pageIndex = index
currentIndex = index
return pageContentViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
func showFirstAlert() { // 그림자 극장 실행 전 플래쉬를 켜달라는 알림 팝업창
let sendAlert = UIAlertView(title: "잠시만요!", message: "그림자극장을 실행하기 전에 플래쉬를 작동해주세요.", delegate: self, cancelButtonTitle: "OK")
sendAlert.show()
}
func showSecondAlert() { // 그림자 극장 실행 전 플래쉬를 켜달라는 알림 팝업창
let sendAlert = UIAlertView(title: "", message: "책장을 넘기듯이 페이지를 넘겨주세요. 메뉴로 돌아가시려면 화면 상단을 터치하세요.", delegate: self, cancelButtonTitle: "OK")
sendAlert.show()
}
}
FirstDataViewController.swift
import UIKit
class FirstDataViewController: UIViewController {
var pageIndex : Int = 0
var titleText : String = ""
var imageFile : String = ""
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor(patternImage: UIImage(named: imageFile)!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
How can I solve this problem?

UIPageViewController crashing when not using static data

I have a working page view controller system with this ( just going to paste absolutely everything, pretty sure the issue just lies in my firebase observation near the top) :
class IndividualPeopleVC: UIViewController, UIPageViewControllerDataSource {
var pageViewController: UIPageViewController!
var pageTitles : [String]!
var imageURLS: NSArray!
let currentUser = FIRAuth.auth()?.currentUser?.uid
override func viewDidLoad()
{
super.viewDidLoad()
self.pageTitles = []
self.pageTitles = ["1", "2", "3", "4'"]
DataService.ds.REF_INTERESTS.child(passedInterest).child("rooms").child(passedRoom).child("users").observeSingleEventOfType(.Value) { (snapshot: FIRDataSnapshot) in
print(snapshot.value)
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
let name = snap.key
let uid = snap.value as! String
let person = Person(name: name, bio: "", UID: uid)
if person.UID != self.currentUser {
self.pageTitles.append(uid)
}
}
}
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
func viewControllerAtIndex(index: Int) -> ContentViewController
{
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
var vc: ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.titleText = self.pageTitles[index] as! String
vc.imageFile = self.pageImages[index] as! String
vc.pageIndex = index
return vc
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?
{
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == 0 || index == NSNotFound)
{
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var vc = viewController as! ContentViewController
var index = vc.pageIndex as Int
if (index == NSNotFound) {
return nil
}
index++
if (index == self.pageTitles.count){
return nil
}
return self.viewControllerAtIndex(index)
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int{
return self.pageTitles.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int{
return 0
}
}
So basically most of that is just copy-pasted from another source and it works. It creates 4 pages from the pageTitles array that scroll and on another VC I am passing the 1,2,3 and 4 and a label is displaying everything in the array as the scrollview should.
The problem comes when I try to not hard-code the pageTitles and instead pull it from firebase.
When I comment out where I'm hard-coding the pageTitles array, I get an unexpected nil value on my ContentViewController where I'm sending the titles and I do like titleLabel.text = (what was sent over).
I figured maybe guarding it with an if/let to allow firebase time to load stuff in would help, so I did a
if let title = (what was sent over) {
titleLabel.text = title
}
Nothing shows up on the screen when this happens, and then if I scroll left or right I get an error with indexes down in my pagebefore/pageafters.
I feel like this should be super simple and very similar to a tableview? Load in data from firebase, fill an array with the info, use if/lets to allow firebase some time to load in, then update the UI based on the array.
I think your DataService is asynchronous. You have to create your pageviewcontroller once your data is ready. Try this modified viewDidLoad method.
override func viewDidLoad()
{
super.viewDidLoad()
self.pageTitles = []
// self.pageTitles = ["1", "2", "3", "4'"]
DataService.ds.REF_INTERESTS.child(passedInterest).child("rooms").child(passedRoom).child("users").observeSingleEventOfType(.Value) { (snapshot: FIRDataSnapshot) in
print(snapshot.value)
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
for snap in snapshots {
let name = snap.key
let uid = snap.value as! String
let person = Person(name: name, bio: "", UID: uid)
if person.UID != self.currentUser {
self.pageTitles.append(uid)
}
}
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let startVC = self.viewControllerAtIndex(0) as ContentViewController
let viewControllers = NSArray(object: startVC)
self.pageViewController.setViewControllers(viewControllers as? [UIViewController], direction: .Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 30, self.view.frame.width, self.view.frame.size.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
}

Black window after returning main view(table view) by tabbar button in iOS

In Root view, I used Tabbar controller and there are 4 tabs.
At first tab View(index = 0), user can search books on open Book API services. It works well, but here is a problem.
1. Users search a book on first tab view (index = 0,tableview)
2. The results come out
3. Users tab other tab button and move other views.
4. Users tab a first button(index=0,table view) for backing to search other books.
5. The Black screen shows up in first tab view, but the user can move to other views by tapping other tabs, there are no black screens. There is a black screen only in the first view(index=0)
What's the problem with my app?
I coded my app with swift.
import Foundation
import UIKit
class SearchHome: UITableViewController, UISearchBarDelegate, UISearchControllerDelegate{
// MARK: - Properties
let searchController = UISearchController(searchResultsController: nil)
// var barButton = UIBarButtonItem(title: "search", style: .Plain, target: nil, action: nil)
let apiKey : String = "cbccaa3f----d980b0c"
var searchString : String = ""
var list = Array<BookAPIresult>()
// MARK: - View Setup
override func viewDidLoad() {
super.viewDidLoad()
self.searchController.searchBar.text! = ""
// Setup the Search Controller
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.dimsBackgroundDuringPresentation = false
searchController.searchBar.searchBarStyle = UISearchBarStyle.Prominent
searchController.searchBar.sizeToFit()
self.tableView.tableHeaderView = searchController.searchBar
// Setup the Scope Bar
searchController.searchBar.scopeButtonTitles = ["title", "hashtag"]
searchController.searchBar.placeholder = "book search"
// Setup Animation for NavigationBar
navigationController?.hidesBarsOnSwipe = true
searchController.hidesNavigationBarDuringPresentation = false
navigationController?.hidesBarsWhenKeyboardAppears = false
navigationController?.hidesBarsOnTap = true
navigationController?.hidesBarsWhenVerticallyCompact = true
self.refreshControl?.addTarget(self, action: #selector(SearchHome.handleRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
// declare hide keyboard tap
let hideTap = UITapGestureRecognizer(target: self, action: #selector(SearchHome.hideKeyboardTap(_:)))
hideTap.numberOfTapsRequired = 1
self.view.userInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
// declare hide keyboard swipe
let hideSwipe = UISwipeGestureRecognizer(target: self, action: #selector(SearchHome.hideKeyboardSwipe(_:)))
self.view.addGestureRecognizer(hideSwipe)
}
// MARK: - UISearchBar Delegate
func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
// filterContentForSearchText(searchBar.text!, scope: searchBar.scopeButtonTitles![selectedScope])
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar){
self.searchString = self.searchController.searchBar.text!
self.list.removeAll()
self.callBookAPI()
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.list.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let row = self.list[indexPath.row]
NSLog("title:\(row.title),row:\(indexPath.row), author:\(row.author)")
let cell = tableView.dequeueReusableCellWithIdentifier("ListCell") as! BookAPIResultCell
cell.title?.text = row.title
cell.author?.text = row.author
dispatch_async(dispatch_get_main_queue(),{ cell.thumb.image = self.getThumbnailImage(indexPath.row)})
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
NSLog("%d",indexPath.row)
}
override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
self.view.endEditing(false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func callBookAPI(){
let encodedSearchString = searchString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let apiURI = NSURL(string: "https://apis.daum.net/search/book?apikey=\(self.apiKey)&q=\(encodedSearchString!)&searchType=title&output=json")
let apidata : NSData? = NSData(contentsOfURL: apiURI!)
NSLog("API Result = %#", NSString(data: apidata!, encoding: NSUTF8StringEncoding)!)
do {
let data = try NSJSONSerialization.JSONObjectWithData(apidata!, options:[]) as! NSDictionary
let channel = data["channel"] as! NSDictionary
// NSLog("\(data)")
let result = channel["item"] as! NSArray
var book : BookAPIresult
for row in result {
book = BookAPIresult()
let title = row["title"] as? String
let decodedTitle = title?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let titleFromHTML = decodedTitle!.html2String
let titleRemoveB = titleFromHTML
let titleRemoveBEnd = titleRemoveB.stringByReplacingOccurrencesOfString("</b>", withString: "")
book.title = titleRemoveBEnd
if let authorEx = row["author"] as? String{
book.author = authorEx
}else{
book.author = ""
}
book.thumbnail = row["cover_s_url"] as? String
//NSLog("\(book.thumbnail)")
let description = row["description"] as? String
let decodedDescription = description?.stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
book.description = decodedDescription!
self.list.append(book)
}
} catch {
NSLog("parse error")
}
}
func getThumbnailImage(index : Int) -> UIImage {
let book = self.list[index]
if let savedImage = book.thumbnailImage {
return savedImage
} else {
if book.thumbnail == "" {
book.thumbnailImage = UIImage(named:
"Book Shelf-48.png")
}else{
let url = NSURL(string: book.thumbnail!)
let imageData = NSData(contentsOfURL: url!)
book.thumbnailImage = UIImage(data:imageData!)
}
return book.thumbnailImage!
}
}
func handleRefresh(refreshControl:UIRefreshControl){
self.searchString = self.searchController.searchBar.text!
self.list.removeAll()
self.callBookAPI()
self.tableView.reloadData()
refreshControl.endRefreshing()
}
// hide keyboard if tapped
func hideKeyboardTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
// hide keyboard if swipe
func hideKeyboardSwipe(recognizer: UISwipeGestureRecognizer) {
self.view.endEditing(true)
}
override func prefersStatusBarHidden() -> Bool {
return false
}
}
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
extension SearchHome: UISearchResultsUpdating {
// MARK: - UISearchResultsUpdating Delegate
func updateSearchResultsForSearchController(searchController: UISearchController) {
let searchBar = searchController.searchBar
let scope = searchBar.scopeButtonTitles![searchBar.selectedScopeButtonIndex]
// filterContentForSearchText(searchController.searchBar.text!, scope: scope)
}
}

PageViewController and screen/data refresh

I'm learning how to use a PageViewController and in the app I'm building I need to be able to refresh the content on the screen from the containing ViewController.
So in my storyboard I have:
a view controller, class RoomPageListViewController.
a view controller, class RoomContentViewController which has a number of labels which are update using CoreData.
a PageViewController
The setup is very simple, I can put in the entire code if needed but what I wanted to do is from RoomPageListViewController to be able to call a function within RoomContentViewController to update the labels and keep the user on the page that they are.
Whatever I tried has resulted in error, for example tried:
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RoomContentViewController") as! RoomContentViewController
pageContentViewController.updateScreen()
But no luck... how can I accomplish this or am I doing it the 'wrong' way?
Thanks!
EDIT v3: With a protocol implementation now working fully!
This is the code for the RoomPageListViewController:
class RoomPageListViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var roomContentVCAccess: RoomContentVCAccess!
var roomsList: Array<String> = ["Entire Home"]
var roomButtonClicked: String = ""
let activityInd: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
var showInd: Bool = true
let shadowLabel: UILabel = UILabel(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
var viewBySelection: Int = 1
var roomDeviceGroupID: Int = 0
var redrawBool: Bool = true
var displayRoom: String = ""
var pageViewController : UIPageViewController!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Devices By Room"
var backBtn : UIBarButtonItem = UIBarButtonItem(title: " ", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
self.navigationItem.leftBarButtonItem = backBtn
self.navigationItem.leftBarButtonItem?.enabled = false
var settingsBtn : UIBarButtonItem = UIBarButtonItem(title: "Settings", style: UIBarButtonItemStyle.Plain, target: self, action: "goSettings")
self.navigationItem.rightBarButtonItem = settingsBtn
activityInd.stopAnimating()
if showInd == true {
startInd()
}
}
func startInd() {
shadowLabel.backgroundColor = UIColor.lightGrayColor()
shadowLabel.text = "Please Wait... Loading Data...\n\n\n\n\n"
shadowLabel.numberOfLines = 6
shadowLabel.textAlignment = NSTextAlignment.Center
let screenSize: CGRect = UIScreen.mainScreen().bounds
shadowLabel.center = CGPoint (x: screenSize.width/2 , y: screenSize.height/2)
shadowLabel.alpha = 0.5
shadowLabel.hidden = false
activityInd.center = CGPoint (x: screenSize.width/2 , y: screenSize.height/2)
activityInd.color = UIColor.blueColor()
activityInd.startAnimating()
activityInd.hidden = false
self.view.addSubview( shadowLabel )
self.view.addSubview( activityInd )
}
func stopInd() {
shadowLabel.hidden = true
activityInd.stopAnimating()
activityInd.hidden = true
showRooms()
if (redrawBool == true) {
//showRooms()
reset()
} else {
self.roomContentVCAccess.updateScreen()
}
redrawBool = false
}
func showRooms() {
roomsList = ["Entire Home"]
var serverSettings:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var managedContext: NSManagedObjectContext = serverSettings.managedObjectContext!
var request = NSFetchRequest(entityName: "Devices")
request.propertiesToFetch = NSArray(objects: "room") as [AnyObject]
request.resultType = NSFetchRequestResultType.DictionaryResultType
request.returnsDistinctResults = true
let deviceFilter = NSPredicate (format: "room <> %#", "Unknown")
request.predicate = deviceFilter
var roomsResults: Array<AnyObject> = managedContext.executeFetchRequest(request, error: nil)!
println("count: \(roomsResults.count)")
if roomsResults.count > 0 {
for room in roomsResults {
var theroom = room["room"] as! String
if (theroom != "Alarm") {
roomsList.append(theroom)
}
}
}
println(roomsList)
}
func reset() {
/* Getting the page View controller */
pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self
let pageContentViewController = self.viewControllerAtIndex(0)
self.pageViewController.setViewControllers([pageContentViewController!], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)
self.pageViewController.view.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
self.addChildViewController(pageViewController)
self.view.addSubview(pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
//stopInd()
}
func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! RoomContentViewController).pageIndex!
index++
return self.viewControllerAtIndex(index)
}
func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
var index = (viewController as! RoomContentViewController).pageIndex!
if (index <= 0) {
return nil
}
index--
return self.viewControllerAtIndex(index)
}
func viewControllerAtIndex(index : Int) -> UIViewController? {
if ((self.roomsList.count == 0) || (index >= self.roomsList.count)) {
return nil
}
let pageContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("RoomContentViewController") as! RoomContentViewController
self.roomContentVCAccess = pageContentViewController
pageContentViewController.room = self.roomsList[index]
pageContentViewController.pageIndex = index
displayRoom = self.roomsList[index]
return pageContentViewController
}
func presentationCountForPageViewController(pageViewController: UIPageViewController) -> Int {
return roomsList.count
}
func presentationIndexForPageViewController(pageViewController: UIPageViewController) -> Int {
return 0
}
}
and the code for RoomContentViewController:
protocol RoomContentVCAccess {
func updateScreen()
}
class RoomContentViewController: UIViewController, RoomContentVCAccess {
var pageIndex: Int?
var room : String!
#IBOutlet weak var screenScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
screenScrollView.contentSize = CGSizeMake(screenScrollView.frame.size.width, 650)
roomName.text = room
btnViewAllRoomSensors.layer.cornerRadius = 10
btnViewAllRoomSensors.layer.masksToBounds = true
updateScreen()
}
override func viewDidAppear(animated: Bool) {
updateScreen()
}
func updateScreen() {
println(room)
let roomValues = getLabelValues(room)
println(roomValues)
var roomDevicesCount: Array<Int> = roomValues[0] as! Array<Int>
// more code here....
}
func getLabelValues(roomName: String) -> (Array<AnyObject>) {
var serverSettings:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var managedContext: NSManagedObjectContext = serverSettings.managedObjectContext!
var request = NSFetchRequest(entityName: "Devices")
let deviceFilter = NSPredicate (format: "room = %#", roomName)
// more CoreData code...
}
The overall picture is that the app, once it receives data calls the stopInd() within RoomPageListViewController. From within stopInd() I need to be able to call updateScreen() that is in RoomContentViewController.
You could create a protocol that the ViewController owning the labels conforms to. For example:
protocol RoomContentVCAccess
{
func updateLabels()
}
Then in your RoomContentViewController's class declaration:
class RoomContentViewController: UIViewController, RoomContentVCAccess
{
// ...
// MARK: - RoomContentVCAccess
func updateLabels()
{
// update your labels
}
}
Your RoomPageListViewController also has to know who his roomContentVCAccess is. For that, just create an instance variable in RoomPageListViewController: var roomContentVCAccess: RoomContentVCAccess! and then say self.roomContentVCAccess = viewController as! RoomContentViewController in your viewControllerAtIndex-function.
And then when stopInd() is called in RoomPageListViewController, say self.roomContentVCAccess.updateLabels().

Resources