I am using SFSafariViewController to open a URL in my iOS app.. it was working perfectly on iOS 9 but after updating my device to iOS 10, it just loads a blank white page with no URL in the address bar. Even safariViewController(controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) is not getting called after controller is presented.
I have imported this in the view controller:
import SafariServices
code:
let url = NSURL(string: urlString)!
if #available(iOS 9.0, *) {
let safariVC = SFSafariViewController(URL: url)
safariVC.delegate = self
self.presentViewController(safariVC, animated: true, completion: {
self.hideHUD()
})
} else {
// Fallback code
}
here is the link to exact same problem someone else faced
Try commenting out any loading animations you are doing and try without that.
...
// self.showHUD()
// self.hideHUD()
...
Its because of a bug in iOS 10 introduced during a security fix which doesn't let safariViewController load when using progress bars and loaders added as a window above the main window
I really wish Apple had documented the change.
I had to comment out the loading indicator in my current app to get it working.
Came across this as seeing some similar problems that I was seeing when trying to use a SafariViewController. Tracked my problems down to using SafariViewController when a popup was present. Have put together some code to show my problem and possible solution.
ViewController.swift:
/*
This view controller tries to boil down to the essence of a problem seen
when trying to use SafariViewController. The net result is DO NOT present
the SafariViewController when a popup is present.
This controller and the associated popup show 3 ways to
present the SafariViewController:
Always Good: This uses a button on the controller to simply call the
showSVC() routine and never had a problem.
Good: This is a work-around for the "Bad" case to follow. In this case,
we are using a button in a popup to bring up the SafariViewController.
The trick is to get rid of the popup before calling showSVC(). This is
done by dismissing the popup immediately without animation and then
adding a delay before calling showSVC(). Seems to work fine, but using
delays to accomplish things always seems a bit suspect. Use at your own risk.
Bad: When this goes bad, a blank white screen is presented with no way
to escape. Using "Reset Content and Settings..." in the simulator can
get one back to where it will work one time. It seemed originally that
this worked on iOS9 but not on iOS10. But now seems to fail similarly
on both iOS9 and iOS10. This case is dismissing the popup with animation
while trying to bring up the SafariViewController.
Other info: This view controller is embedded in a navigation controller -
basically to provide a navigation bar and button to act as the anchor
point for the popup. The popup provides two buttons that call back
to this controller with the "PopButtonPressedProtocol". This controller
uses the title in the popup's buttons to differentiate the "good" and
"bad" cases.
The problems shown by this example sounded similar to problems various
others reported, but these reports may be for other reasons, which may
or may not be similar.
*/
import UIKit
import SafariServices
class ViewController: UIViewController, UIPopoverPresentationControllerDelegate, PopButtonPressedProtocol {
#IBOutlet weak var btnAlwaysGood: UIButton!
#IBOutlet weak var btnPopup: UIBarButtonItem!
let webAddr = "http://www.google.com"
func delay(_ delay: Double, closure:#escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
func showSVC() {
let svc = SFSafariViewController(url: URL(string: webAddr)!)
self.present(svc, animated: true, completion: nil)
}
func popButtonPressed(_ button: UIButton) {
if let title = button.currentTitle {
switch title {
case "Bad":
dismiss(animated: true, completion: nil)
showSVC()
case "Good":
dismiss(animated: false, completion: nil)
delay(0.5, closure: { self.showSVC() })
default:
break
}
}
}
func popupButtonPressed() {
performSegue(withIdentifier: "popup", sender: nil)
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { // Needed for popup
return .none
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
btnAlwaysGood.addTarget(self, action: #selector(showSVC), for: .touchUpInside)
btnPopup.target = self
btnPopup.action = #selector(popupButtonPressed)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? PopVC {
vc.delegate = self
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 60, height: 100)
if let popover = vc.popoverPresentationController {
popover.permittedArrowDirections = .any
popover.delegate = self
popover.barButtonItem = navigationItem.rightBarButtonItem
}
}
}
}
PopVC.swift:
import UIKit
protocol PopButtonPressedProtocol : class {
func popButtonPressed(_ button: UIButton) // protocol:
}
class PopVC: UIViewController {
#IBOutlet weak var btnBad: UIButton!
#IBOutlet weak var btnGood: UIButton!
weak var delegate : PopButtonPressedProtocol?
func buttonPressed(_ button: UIButton) {
delegate?.popButtonPressed(button)
}
override func viewDidLoad() {
super.viewDidLoad()
btnBad.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
btnGood.addTarget(self, action: #selector(buttonPressed(_:)), for: .touchUpInside)
}
}
Swift 5.2, Xcode 11.4
I had similar problem, what I was doing is I was presenting UIAlertViewController and on action of its button I was present SFSafariController....this code worked perfectly on iOS 13 but iOS 12 gave problem.... apparently I had to dismiss the UIAlertViewController first before presenting SFSafariController. Hope this helps.
or else quick fix would be to use UIApplication.shared.openURL()
Related
I'm a beginner trying to learn iOS.
I'm trying to show a sheet, but I'm finding it's not really showing anything.
This is what it looks like:
This is my relevant code:
class ViewController: UIViewController {
#IBAction func openMemoryLog(_ sender: UIButton) {
let memoryLogViewController = MemoryLogViewController()
present(memoryLogViewController, animated: true)
}
}
class MemoryLogViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
print("Memory log loaded")
if let presentationController = presentationController as? UISheetPresentationController {
presentationController.detents = [ .medium() ]
}
}
}
I can see the print statement going through, so it's at least loading. But don't know what's going on here. Looks like some sort of modal thing is happening, but the IB interface isn't showing.
When you use Storyboard / IB to design an interface, you have to instantiate that controller from the Storyboard - you cannot simply assign the class to a variable.
#IBAction func openMemoryLog(_ sender: UIButton) {
// if you designed MemoryLogViewController in Storyboard,
// you cannot create it like this:
//let memoryLogViewController = MemoryLogViewController() <-- wrong
// you need to instantiate it from the Storyboard
// for example, if you gave your controller a Storyboard ID of "memoryLogViewController":
if let memoryLogViewController = storyboard?.instantiateViewController(withIdentifier: "memoryLogViewController") {
present(memoryLogViewController, animated: true)
}
}
I know this is a pretty common question but I've tried the various solutions offered here (that are not too old) and in numerous tutorials and I just can't seem to find out why it's still failing for me. Basically setting sendingViewController.delegate to self ends up being nil in sendingViewController. I understand this is very likely because the reference to the sendingViewController is being disposed of. But here is why I'm asking this again.
First, almost every tutorial and every other StackOverflow post is wiring up the mainViewController and the sendingViewController differently. I'm trying to make this work through a Navigation Controller, what one would think is the most common pattern for this.
In the app I'm building (which is more complex than the sample I'm going to show), the mainViewController calls the Settings viewController through a right navbar button. Then the user can select items from a list, which opens a controller with a searchBar and a tableView of items to select from. I need that third view controller to return the selected item from the table view to the settings screen. I'm using storyboards as well. I'm fairly new to Swift and I'm not ready to do all this "programmatically". Any way in the sending view controller, my delegate which should have been set in the calling view controller is nil and I can't invoke the protocol function in the main view controller to pass the data back.
I did a tutorial directly (not using Nav controllers) and I got that to work, but the moment I deviate away, it starts failing. I then put together a streamlined project with two view controllers: ViewController and SendingViewController. ViewController was embedded in a navigation controller and a right bar button was added to go to the SendingViewController. The SendingViewController has a single UI Button that attempts to call the protocol function and dismiss the SendingViewController. I'm not using Seque's, just a simple buttons and protocol/delegate pattern as I can.
My question is what am I missing to actually set the SendingViewController.delegate correctly?
Here's some code:
//ViewController.swift
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var showDataLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func fetchDataButton(_ sender: UIBarButtonItem) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "SendingViewController") as! SendingViewController
controller.delegate = self
print("fetching data")
present(controller, animated: true, completion: nil)
}
}
extension ViewController: SendingViewControllerDelegate {
func sendData(value: String) {
print("got Data \(value)")
self.showDataLabel.text = value
}
}
and
// SendingViewController.swift
import UIKit
protocol SendingViewControllerDelegate {
func sendData(value: String)
}
class SendingViewController: UIViewController {
var delegate: SendingViewControllerDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func sendDataButton(_ sender: UIButton) {
print("attempting to send data \(self)")
print("to \(self.delegate)")
self.delegate?.sendData(value: "Hello World")
self.navigationController?.popViewController(animated: true)
}
}
Here is a screenshot of the Storyboard:
The ChildViewController does have a storyboard id name of "ChildViewController". All buttons and labels have their appropriate IBOutlet and IBAction's set up.
Help!
i copy paste your code .. its working perfect .. i make just one change
instead of pop you need to use dismiss as you are presenting from your base viewController
#IBAction func sendDataButton(_ sender: UIButton) {
print("attempting to send data \(self)")
print("to \(self.delegate)")
self.delegate?.sendData(value: "Hello World")
self.dismiss(animated: true, completion: nil)
}
here is the project link we.tl/t-NUxm9D26XN
I managed to get this working. In the receiving/parent view controller that needs the data:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination as! sendingViewController
controller.cityDelegate = self
}
Then in the sending view controller in my tableView did select row function:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
let city = filtered[indexPath.row]
searchBar.resignFirstResponder()
self.navigationController?.popViewController(animated: true)
self.cityDelegate?.addCity(city)
self.dismiss(animated: true, completion: nil)
}
I don't think I should be both popping the view controller and dismissing it, but it works. Also in the view controller I did this:
private var presentingController: UIViewController?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
presentingController = presentingViewController
}
override func didMove(toParent parent: UIViewController?) {
super.didMove(toParent: parent)
if parent == nil {
}
}
I don't know if I really need this didMove() or not since it doesn't really do anything.
But some combination of all this got it working.
In my other app I'm not using a navigation bar controller and the standard delegate/protocol method works like a charm.
I'm trying to define a popover view attached to a view like this:
Here's my code:
class MyController: UIViewController, UIPopoverPresentationControllerDelegate {
...
func displaySignOut(_ sender: UIButton) {
let vc = UIStoryboard(name: "Main", bundle: nil)
.instantiateViewController(withIdentifier: "signOutPopover")
vc.modalPresentationStyle = .popover
vc.preferredContentSize = CGSize(width: 100, height: 30)
present(vc, animated: true, completion: nil)
let pc = vc.popoverPresentationController!
pc.sourceView = sender
pc.sourceRect = sender.bounds
pc.delegate = self
}
func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle {
return .none
}
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
Because the popover is so small, I'd like to use this style on all devices. I've followed the usual advice (e.g., here) on overriding adaptivePresentationStyle to return UIModalPresentationStyle.none.
This works fine on iPad devices, but on iPhones, it doesn't. On smaller iPhone devices, it comes up full screen all the time. On larger screens (e.g., iPhone 7 Plus), it comes up wrong, but, weirdly, switches to a popover presentation (in both portrait and landscape) if I rotate the device after the popover appears. (If I dismiss the popover and bring it up again, it's wrong again until I rotate the device.) Furthermore, in landscape it comes up in a strange configuration (not full screen as in portrait):
Unlike with a popover presentation, this does not dismiss if I tap outside the popover view itself.
The Apple documentation says (in part):
In a horizontally compact environment, popovers adapt to the UIModalPresentationOverFullScreen presentation style by default.
The "by default" strongly suggests that there's a way to override this behavior. But (as is consistent with this post), overriding adaptivePresentationStyle in the delegate doesn't seem to be the way to do this any more (although it used to work). So is there a new way to modify the default behavior?
I'm using XCode 8.3.3 and Swift 3.1, targeting iOS 9+.
I have created one custom class with storyboard inside that connect
outlet of button and implemented below code.
import UIKit
class PopOverViewController: UIViewController {
#IBOutlet weak var button: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
button.backgroundColor = UIColor.purple
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Updating the popover size
override var preferredContentSize: CGSize {
get {
let size = CGSize(width: 80, height: 60)
return size
}
set {
super.preferredContentSize = newValue
}
}
//Setup the ViewController for popover presentation
func updatePopOverViewController(_ button: UIButton?, with delegate: AnyObject?) {
guard let button = button else { return }
modalPresentationStyle = .popover
popoverPresentationController?.permittedArrowDirections = [.any]
popoverPresentationController?.backgroundColor = UIColor.purple
popoverPresentationController?.sourceView = button
popoverPresentationController?.sourceRect = button.bounds
popoverPresentationController?.delegate = delegate
}
}
And then Inside ViewController implemented one function to show
popOver on iphone
func showPopOver(button: UIButton!) {
let viewController = PopOverViewController()
viewController.updatePopOverViewController(button, with: self)
present(viewController, animated: true, completion: nil)
}
Note:- Tested and this should work on Portrait as well Landscape mode
iOS 15 has some new ways to solve this problem.
Take a look at the WWDC21 Session "Customize and Resize Sheets in UIKit" https://developer.apple.com/wwdc21/10063
Pretty simple new interface for popovers and customized sheets. Shows how to do non-modal interaction with pop over and the view behind it.
I am using Swift 2 in Xcode 7.0 beta 6
Long story short, I am trying to work out how to set .navigationBar.barStyle and navigationBar.tintColor when using a document picker to access iCloud - i.e. a UIDocumentPickerViewController.
I have tried e.g. :
/...
documentPicker.navigationController!.navigationBar.barStyle = UIBarStyle.Default
documentPicker.navigationController!.navigationBar.tintColor = UIColor.orangeColor()
/...
For example. Here I have a view controller embedded within a navigation controller:
In MyNavigationController I can set the .barStyle and .tintStyle as follows:
class MyNavigationController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.barStyle = UIBarStyle.Default
self.navigationBar.tintColor = UIColor.orangeColor()
}
}
So .tintStyle is orange as follows:
iCloud is enabled and FirstViewController conforms to UIDocumentPickerDelegate. The bar button calls an IBAction function as shown here in the code for FirstViewController:
class FirstViewController: UIViewController, UIDocumentPickerDelegate {
// ...
#IBAction func importDocument(sender: UIBarButtonItem) {
let documentPicker: UIDocumentPickerViewController = UIDocumentPickerViewController(documentTypes: ["public.text"], inMode: UIDocumentPickerMode.Import)
documentPicker.delegate = self
documentPicker.modalPresentationStyle = UIModalPresentationStyle.FullScreen
documentPicker.popoverPresentationController?.barButtonItem = sender
self.presentViewController(documentPicker, animated: true, completion: nil)
}
func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
// ...
}
func documentPickerWasCancelled(controller: UIDocumentPickerViewController) {
// ...
}
}
That works. The document picker loads as expected:
BUT. For the sake of working out how to do this, I want the menu item "Done" to be orange. Like the previous.
I have tried adding the following code to the #IBAction as follows:
//...
documentPicker.navigationController!.navigationBar.barStyle = UIBarStyle.Default
documentPicker.navigationController!.navigationBar.tintColor = UIColor.orangeColor()
self.presentViewController(documentPicker, animated: true, completion: nil)
//...
That doesn't work because at this point documentPicker.navigationController is nil.
Can anyone tell me how or where in the cycle I can access documentPicker.navigationController!.navigationBar.tintColor?
Or perhaps I am missing something and there is some other way of changing the menu color?
Or perhaps I should be looking to create a custom navigation controller - and a custom document picker view controller. Then in theory I would be able to access a relevant viewDidLoad. I tried that but realised that I would then also need a custom version of the UIDocumentPickerDelegate protocol. There must surely be an easier solution (and I had doubts as to whether that would be allowed).
You can alter navigationBar default tint color via UIAppearance:
UINavigationBar.appearance().tintColor = UIColor.orangeColor()
swift 3,4 and xcode 9+ :
documentPicker.view.tintColor = .orange
I'm trying to add a simple popoverController to my iphone app, and I'm currently struggling with the classic "blank screen" which covers everything when I tap the button.
My code looks like this:
#IBAction func sendTapped(sender: UIBarButtonItem) {
var popView = PopViewController(nibName: "PopView", bundle: nil)
var popController = UIPopoverController(contentViewController: popView)
popController.popoverContentSize = CGSize(width: 3, height: 3)
popController.presentPopoverFromBarButtonItem(sendTappedOutl, permittedArrowDirections: UIPopoverArrowDirection.Up, animated: true)
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle {
// Return no adaptive presentation style, use default presentation behaviour
return .None
}
}
The adaptivePresentationStyleForPresentationController-function was just something I added because I read somewhere that this is what you need to implement to get this function on the iphone. But still: there is still a blank image covering the whole screen, and I do not know how to fix it.
Any suggestions would be appreciated.
The solution I implemented for this is based on an example presented in the 2014 WWDC session View Controller Advancements in iOS 8 (see the slide notes). Note that you do have to implement the adaptivePresentationStyleForPresentationController function as a part of the UIPopoverPresentationControllerDelegate, but that function should be outside of your sendTapped function in your main view controller, and you must specify UIPopoverPresentationControllerDelegate in your class declaration line in that file to make sure that your code modifies that behaviour. I also took the liberty to separate out the logic to present a view controller in a popover into its own function and added a check to make sure the function does not present the request view controller if it is already presented in the current context.
So, your solution could look something like this:
// ViewController must implement UIPopoverPresentationControllerDelegate
class TheViewController: UIViewController, UIPopoverPresentationControllerDelegate {
// ...
// The contents of TheViewController class
// ...
#IBAction func sendTapped(sender: UIBarButtonItem) {
let popView = PopViewController(nibName: "PopView", bundle: nil)
self.presentViewControllerAsPopover(popView, barButtonItem: sender)
}
func presentViewControllerAsPopover(viewController: UIViewController, barButtonItem: UIBarButtonItem) {
if let presentedVC = self.presentedViewController {
if presentedVC.nibName == viewController.nibName {
// The view is already being presented
return
}
}
// Specify presentation style first (makes the popoverPresentationController property available)
viewController.modalPresentationStyle = .Popover
let viewPresentationController = viewController.popoverPresentationController?
if let presentationController = viewPresentationController {
presentationController.delegate = self
presentationController.barButtonItem = barButtonItem
presentationController.permittedArrowDirections = .Up
}
viewController.preferredContentSize = CGSize(width: 30, height: 30)
self.presentViewController(viewController, animated: true, completion: nil)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController) -> UIModalPresentationStyle {
return .None
}
}
Real world implementation
I implemented this approach for input validation on a sign up form in an in-progress app that I host on Github. I implemented it as extensions to UIVIewController in UIViewController+Extensions.swift. You can see it in use in the validation functions in AuthViewController.swift. The presentAlertPopover method takes a string and uses it to set the value of a UILabel in a GenericAlertViewController that I have set up (makes it easy to have dynamic text popovers). But the actual popover magic all happens in the presentViewControllerAsPopover method, which takes two parameters: the UIViewController instance to be presented, and a UIView object to use as the anchor from which to present the popover. The arrow direction is hardcoded as UIPopoverArrowDirection.Up, but that wouldn’t be hard to change.