Failed when present UIviewcontroller - uiviewcontroller

I have 2 viewcontrollers: mainVC & listVC.
I tapped customized button on mainVC to present listVC, then tapped button on listVC to go back to mainVC. until now there is no any failure. But when I tap customized button to go to listVC again, program failed.
error:
NSInvalidArgumentException', reason: 'Application tried to present modal view controller on itself. Presenting controller is
Voice_of_Animals.ListVC: 0x7feeee513210>
class ViewController: UIViewController
{
var cb = CirButton(Circolor: UIColor.cyan, Rsize: 100, PositionX: 100, PositionY: 100)
override func viewDidLoad() {
super.viewDidLoad()
mainVC = self
self.view.addSubview(cb)
listVC.transitioningDelegate = listVC as UIViewControllerTransitioningDelegate
}
func showNextPage() {
self.present(listVC, animated: true, completion: nil)
}
#IBAction func show(_ sender: UIButton) {
self.present(listVC, animated: true, completion: nil)
}
#IBAction func Touch(_ sender: CButton) {
sender.RunAnimation()
}
override func didReceiveMemoryWarning() {
}
}
class ListVC: ViewController{
var transition = FadeAnimator()
var btn1 = CirButton(Circolor: UIColor.cyan, Rsize: 100, PositionX: 100, PositionY: 100)
#IBOutlet weak var myList: ListView!
#IBAction func Push(_ sender: UIButton) {
}
#IBAction func edgeSlide(_ sender: UIScreenEdgePanGestureRecognizer) {
mainVC.dismiss(animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(btn1)
}
}

Related

Present tab bar controller based on a set of conditions

In, one of my multiple UIViewControllers, I have a sign in button that takes you to a tab bar scene. The viewcontrollers shown in the tab bar scene depends on the type of account selected. In another scene, there's a button which updates it's titlelabel based on type of account. Here is what I have done.
class SIgn_In: UIViewController {
let tabbar = UITabBarController()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func didTapSignIn(_ sender: Any) {
guard let vc = storyboard?.instantiateViewController(identifier: "vc") as? AccountViewController else{return}
let firstVc = First()
let secondVc = Second()
let thirdVc = Third()
if vc.text == "accountType1" {
tabbar.setViewControllers([firstVc,secondVc], animated: false)
} else if vc.text == "accounttype2" {
tabbar.setViewControllers([thirdVc,firstVc,secondVc], animated: false)
}
present(tabbar,animated: true)
}
In the accountViewController, I have this code.
class AccountViewController: UIViewController {
#IBOutlet weak var button: UIButton!
public var accountType:String = ""
override func viewDidLoad() {
super.viewDidLoad()
accountType = button.currentTitle!
}
But I'm not quite getting what I expected, what am I missing? Please help

webview executing one of both urls

I'm doing a dictionary application. Some terms have animation, some don't. If ;
let url = URL(string: "http://bsstech.site/-Sozlukler/Fizik/(f.animasyonAdi ?? "").html")!
webview.load(URLRequest(url: url))
or let url = URL(string: "http://bsstech.site/-Sozlukler/Fizik/logo.html")!
webview.load(URLRequest(url: url)) I want to run.
Did I write the code as below, but I did not get the result I wanted.
if let f = fizik {
if (f.animasyonAdi != nil) {
let url = URL(string: "http://bsstech.site/-Sozlukler/Fizik/\(f.animasyonAdi ?? "").html")!
webview.load(URLRequest(url: url))
}else {
let url = URL(string: "http://bsstech.site/-Sozlukler/Fizik/logo.html")!
webview.load(URLRequest(url: url))
}
navigationItem.title = f.baslik
aciklama.text = f.aciklama
}
}
I would be very glad if you help.
Step 1: Create a WebViewViewController
Step 2: Added WebKitView, top title label, a cross button and activity IndicatorView in the WebViewVC.xib file, then insert outlets in the WebViewVC.swift
Step 3: Implement logic in the WebViewVC.swift like the following:
import UIKit
import WebKit
class WebViewVC: UIViewController {
// MARK: - Outlets
#IBOutlet private weak var webView: WKWebView!
#IBOutlet private weak var activityIndicatorView: UIActivityIndicatorView!
#IBOutlet private weak var titleLabel: UILabel!
// MARK: - Variables
private let userAgentValue = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
var navTitle: String?
var urlString: String?
// MARK: - View Cycle
override func viewDidLoad() {
super.viewDidLoad()
initView()
setupWebView()
loadData()
}
// MARK: - Event
#IBAction private func actionTapToCloseButton(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Setting up View Controller
extension WebViewVC {
private func initView() {
titleLabel.text = navTitle
}
private func setupWebView() {
webView.navigationDelegate = self
webView.customUserAgent = userAgentValue
webView.isMultipleTouchEnabled = true
webView.isUserInteractionEnabled = true
}
private func loadData() {
if let `urlString` = urlString, !urlString.isEmpty, let query = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed), let url = URL(string: query) {
let request = URLRequest(url: url)
webView.load(request)
}
}
}
// MARK: - WKNavigationDelegate
extension WebViewVC: WKNavigationDelegate {
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicatorView.startAnimating()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicatorView.stopAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
ShowPopUps.showDefaultAlert(title: "", message: "\(error.localizedDescription)", negativeActionText: "Ok")
activityIndicatorView.stopAnimating()
}
}
Step 4: Just Call
if let f = fizik {
var urlString: String? = nil
if (f.animasyonAdi != nil) {
urlString = http://bsstech.site/-Sozlukler/Fizik/\(f.animasyonAdi ?? "").html"
} else {
urlString = "http://bsstech.site/-Sozlukler/Fizik/logo.html"
}
let vc = WebViewVC()
vc.urlString = urlString
vc.navTitle = f.baslik
present(vc, animated: true, completion: nil)
}

Passing ImageArray from Json File to ImageView Controller

I'm Trying to have tableview with a search controller pass image Array from Json file to a new viewcontroller based on what option the user picks in search bar tableview. I have created a search bar for my App that displays will display all of the information in the app so the user can easily pick the pictures they want to see. That works normally by using a tableview, and when the user pick a row, it sends a variable with the associated pictures to an image view on the other screen.
Because of the amount of options I have, I created a Json file. I have it coded where it will return options based on what the user types into the search bar. My problem is that I am unable to pass the Image Array from the .json file to the image view controller. It will display the viewcontroller, but the "array" imageview is blank as no picture array is being passed. Below is my code and am wondering if anyone has any ideas that could point me in the right direction, or tell me what I am doing wrong.
Search Bar code:
import UIKit
class ProtocolCell: UITableViewCell {
#IBOutlet weak var pNameLabel: UILabel!
}
extension String {
func trimmed() -> String {
return self.trimmingCharacters(in: .whitespaces)
}
}
class SearchController: UIViewController, UISearchBarDelegate {
/// Search Bar
#IBOutlet weak var pSearchBar: UISearchBar!
/// Proto Array
fileprivate var myProtocols:[Protocols]?
/// Searhed Array
fileprivate var searchedProtocols:[Protocols]?
/// TableView
#IBOutlet weak var protocolsTV: UITableView!
/// Is Searching
fileprivate var isSearching:Bool=false
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
protocolsTV.tableFooterView=UIView()
pSearchBar.delegate=self
myProtocols=[Protocols]()
searchedProtocols=[Protocols]()
myProtocols?.removeAll()
searchedProtocols?.removeAll()
myProtocols=Functions.getAllProtocolsFromJson()
if protocolsTV.delegate == nil {
protocolsTV.delegate=self
protocolsTV.dataSource=self
}
protocolsTV.reloadData()
}
}
extension SearchController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return isSearching == false ? (myProtocols?.count ?? 0) : (searchedProtocols?.count ?? 0)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ProtocolCell") as! ProtocolCell
cell.pNameLabel.text=isSearching == false ? (myProtocols![indexPath.row].pName ?? "") : (searchedProtocols![indexPath.row].pName ?? "")
return cell
}
//EDIT TABLE FUNCTION HERE!!!!!//
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Is Searching: \(isSearching) ImagesArray: \(isSearching==true ? (searchedProtocols?[indexPath.row].imagesName ?? []) : (myProtocols?[indexPath.row].imagesName ?? []))")
let Vc = self.storyboard?.instantiateViewController(withIdentifier: "imageViewController") as! imageViewController
let home = self.storyboard?.instantiateViewController(withIdentifier: "FIRST") as! ViewController
//switch indexPath.section
// {
// case 0:
if searchedProtocols?[indexPath.row].pName == "test" {
let arrayStorage = myProtocols?[indexPath.row].imagesName ?? []
Vc.passedArray = arrayStorage
print(arrayStorage)
print(myProtocols?[indexPath.row].imagesName ?? [])
self.navigationController?.pushViewController(Vc, animated: true)
}
else {
self.navigationController?.pushViewController(home, animated: true)
}
// break;
// default:
// self.navigationController?.pushViewController(home, animated: true)
// }
}
func updateSearchData(With searchText: String, In searchBar: UISearchBar) {
if searchText.trimmed().count == 0 {
isSearching=false
searchBar.setShowsCancelButton(false, animated: true)
} else {
isSearching=true
searchBar.setShowsCancelButton(true, animated: true)
}
if isSearching {
/// We Are Searching Sort Array
if searchedProtocols == nil { searchedProtocols=[Protocols]() }
searchedProtocols?.removeAll()
searchedProtocols=myProtocols!.filter({($0.pName ?? "").lowercased().contains(searchText.lowercased())})
/// Make Set So, Data isn't Repeated
searchedProtocols=Array(Set(searchedProtocols ?? []))
} else {
/// Searching is Stopped
searchedProtocols?.removeAll()
}
protocolsTV.reloadData()
}
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
updateSearchData(With: searchText, In: searchBar)
}
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
self.view.endEditing(true)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
searchBar.setShowsCancelButton(false, animated: true)
searchBar.text=nil
isSearching=false
searchedProtocols?.removeAll()
protocolsTV.reloadData()
self.view.endEditing(true)
}
}
Other Used Code:
class Protocols: NSObject {
var pName:String?
var imagesName:[UIImage]!
override init() {}
init(With Dict: [String:Any]) {
pName=Dict["name"] as? String ?? ""
imagesName=Dict["imagesArray"] as? [UIImage] ?? []
}
ImageViewController:
class imageViewController: UIViewController,GADBannerViewDelegate, UIGestureRecognizerDelegate, UIScrollViewDelegate {
#IBOutlet weak var pageControl: UIPageControl!
var bannerView: GADBannerView!
var index = 0
var mySelectedProtocol:Protocols?
#IBOutlet weak var scrollView: UIScrollView!
#IBOutlet weak var myImageView: UIImageView!
#IBAction func pictureSwipe(_ sender: Any) {
let pictureString = self.passedArray[index]
self.myImageView.image = pictureString
index = (index < passedArray.count-1) ? index+1 : 0
self.pageControl.numberOfPages = passedArray.count
self.pageControl.currentPage = index
}
#IBAction func pictureswipeback(_ sender: Any) {
let pictureString = self.passedArray[index]
self.myImageView.image = pictureString
index = (passedArray.count-1)
self.pageControl.numberOfPages = passedArray.count
self.pageControl.currentPage = index
}
func configurePageControl() {
self.pageControl.numberOfPages = passedArray.count
self.pageControl.currentPage = 0
self.pageControl.pageIndicatorTintColor = UIColor.white
self.pageControl.currentPageIndicatorTintColor = UIColor.red
self.view.addSubview(pageControl)
if index == 1 {
self.pageControl.currentPage = 1
}
func updateCurrentPageDisplay(){
self.pageControl.numberOfPages = passedArray.count
}
}
var passedImage : UIImage! = nil
var passedArray : [UIImage]!
override func viewDidLoad(){
super.viewDidLoad()
self.myImageView.image = passedArray.first
configurePageControl()
scrollView.delegate = self
self.navigationController?.navigationBar.isHidden = false
scrollView.minimumZoomScale = 1.0
scrollView.maximumZoomScale = 5.0
In Destination Controller
class DestinationVC: UIViewController {
var mySelectedProtocol:Protocols?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if mySelectedProtocol == nil { self.navigationController?.popViewController(animated: true) }
/// We have Data
print("Img Array with Name ==> \(mySelectedProtocol?.imagesName ?? [])")
}
}
In Source Controller TableView Delegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
print("Is Searching: \(isSearching) ImagesArray: \(isSearching==true ? (searchedProtocols?[indexPath.row].imagesName ?? []) : (myProtocols?[indexPath.row].imagesName ?? []))")
let vc:DestinationVC=mainStoryBoard.instantiateViewController(withIdentifier: "DestinationVC") as! DestinationVC
vc.mySelectedProtocol=isSearching==true ? (searchedProtocols?[indexPath.row]) : (myProtocols?[indexPath.row])
self.navigationController?.pushViewController(vc, animated: true)
}
Update 2 - Show Images as PageViewController
private func addPageView() {
myScrollView.backgroundColor=UIColor.clear
myScrollView.isUserInteractionEnabled=true
myScrollView.showsHorizontalScrollIndicator=false
myScrollView.isPagingEnabled=true
myScrollView.delegate=self
myScrollView.bounces=false
self.count=mySelectedProtocol!.imagesName!.count
for i in 0..<self.count {
///Get Origin
let xOrigin : CGFloat = CGFloat(i) * myScrollView.frame.size.width
///Create a imageView
let imageView = UIImageView()
imageView.frame = CGRect(x: xOrigin, y: 0, width: myScrollView.frame.size.width, height: myScrollView.frame.size.height)
imageView.contentMode = .scaleAspectFit
imageView.image=UIImage(named: mySelectedProtocol!.imagesName![i])
myScrollView.addSubview(imageView)
}
setUpPageControl()
///Set Content Size to Show
myScrollView.contentSize = CGSize(width: myScrollView.frame.size.width * CGFloat(self.count), height: myScrollView.frame.size.height)
}

How to call a function inside a function in Swift 3

I try to call a function tapBlarButton(_ sender: UITapGestureRecognizer) in viewWillAppear function but I don't know how to do it, this is my code:
#IBOutlet weak var buttonFunction: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(tapBlarButton(_:)))
buttonFunction.addGestureRecognizer(tapGesture)
}
func tapBlarButton(_ sender: UITapGestureRecognizer) {
print("Hello! 😘")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Here I want to call the function
}

Disable swipe gesture in QLPreviewController

I am trying to preview the Images/Video/PDF in UICollectionViewCell (full screen).
for PDF I am trying to use the QuickLook framework.
Here is what I am trying to do,
CollectionView
CollectiViewCell
QLPreviewController.view as subview of CollectionView.contentView
and other cells will be simple UIImageViews.
So when I scroll right/left the touches are always consumed by QLPreviewController and I am unable to navigate to next cell.
I tried adding subview after adding qlpreviewcontroller.view (to intercept touches)
The Implementation follows:
class SampleView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
return nil
}
}
class SCGalleryCollectionViewCell: UICollectionViewCell,UIScrollViewDelegate, QLPreviewControllerDataSource {
var quickLookController : PreviewController!
var scrollView : UIScrollView!
var imageView : SCImageView!
override init(frame: CGRect) {
super.init(frame: frame)
let sampleView = SampleView()
sampleView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(sampleView)
sampleView.fillHorizontally()
sampleView.fillVertically()
sampleView.backgroundColor = UIColor.greenColor()
contentView.bringSubviewToFront(sampleView)
quickLookController = PreviewController()
quickLookController.dataSource = self
// quickLookController.view.frame = CGRectMake(0, 0, 100, 100)
quickLookController.view.translatesAutoresizingMaskIntoConstraints = false
sampleView.addSubview(quickLookController.view)
quickLookController.view.fillVertically()
quickLookController.view.fillHorizontally()
quickLookController.view.userInteractionEnabled = false
quickLookController.view.gestureRecognizers = nil
}
}
class PreviewController: QLPreviewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
view.userInteractionEnabled = false
view.exclusiveTouch = false
view.multipleTouchEnabled = false
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
}
func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
return false
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
}
So my question is, how can I disable the swipe gesture on qlpreviewcontroller ?
Thanks in advance!!