// In UITableViewCell
// when I tab on screen it says "open image
2017-11-22 13:15:31.023129+0530 chat[1376:265960] Warning: Attempt to present on whose view is not in the window hierarchy!"
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.window?.rootViewController?.present(vc, animated: true, completion: nil)
}
You need to get the top presented view controller and then present.
Try this.
func topViewController() -> UIViewController? {
if var topController = UIApplication.shared.keyWindow?.rootViewController {
while let presentedViewController = topController.presentedViewController {
topController = presentedViewController
}
return topController
}
return nil
}
func imageTapped(tapGestureRecognizer: UITapGestureRecognizer)
{
let tappedImage = tapGestureRecognizer.view as! UIImageView
print("open image")
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc : openimageinfullscreen = sb.instantiateViewController(withIdentifier: "openimageinfullscreen") as! openimageinfullscreen
self.topViewController()?.present(vc, animated: true, completion: nil)
}
On a separate note, You shouldn't use class name starts with small letter. openimageinfullscreen class should be OpenImageInFullscreen
Related
import AVFoundation
import UIKit
import AVKit
class Class1: UIViewController {
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
var playerTimer = NSTimer()
override func viewDidAppear(animated:Bool) {
let fileURL = NSURL(fileURLWithPath: "file.mp4")
playerView = AVPlayer(URL: fileURL)
playerViewController.player = playerView
self.presentViewController(playerViewController, animated: true){
self.playerViewController.player?.play()
self.playerTimer = NSTimer.scheduledTimerWithTimeInterval(4.0, target: self, selector:Selector("stopAfter4seconds:"), userInfo: nil, repeats: false)
}
}
func stopAfter4seconds(timer: NSTimer){
self.playerViewController.player?.pause()
self.playerViewController.player = nil
self.presentingViewController?.dismissViewControllerAnimated(false, completion: nil)
self.presentViewController(GameViewController1(), animated: false, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
My Problem is that when I present the line:
self.presentViewController(GameViewController1(), animated: false, completion: nil)
I Get the error "attempt to present GameViewController1... whose view is not in the window hierarchy!"
I made sure to play it in viewDidAppear as to add it to the view hierarchy but it doesn't seem to do so
[Update] Okay i realize now that I'm presenting the avplayerviewcontroller and then trying to play the next view controller after. How exactly do I "Dismiss" the AVplayerviewcontroller as well have my next view in the right window hierarchy???
ANSWER: I was presenting my next view with 'self.' instead of with the view controller that was present, which happened to be the playerViewController so this line of code worked for me.
playerViewController.presentViewController(GameViewController1(),
animated: false, completion: nil)
I'm trying to make this posting app similar to instagram but I am getting stuck on a issue once i press my compose button. This button is suppose to post the image but instead its crashing. I'm having an error after I try to upload a caption\image with my app here:
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
It is giving me this error:EXE_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
Please help!
#IBOutlet weak var captionTextView: UITextView!
#IBOutlet weak var previewImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
captionTextView.delegate = self
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func addImageTapped(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
imagePicker.mediaTypes = UIImagePickerController.availableMediaTypesForSourceType(.PhotoLibrary)!
imagePicker.allowsEditing = false
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
self.previewImage.image = image
self.dismissViewControllerAnimated(true, completion: nil)
}
func textViewShouldEndEditing(textView: UITextView) -> Bool {
captionTextView.resignFirstResponder()
return true;
}
#IBAction func composeTapped(sender: AnyObject) {
let date = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
dateFormatter.dateStyle = NSDateFormatterStyle.ShortStyle
let localDate = dateFormatter.stringFromDate(date)
let imageToBeUploaded = self.previewImage.image
let imageData = UIImagePNGRepresentation(imageToBeUploaded!)!
let file: PFFile = PFFile(data: imageData)!
let fileCaption: String = self.captionTextView.text
let photoToUpload = PFObject(className: "Posts")
photoToUpload["Image"] = file
photoToUpload["Caption"] = fileCaption
photoToUpload["addedBy"] = PFUser.currentUser()?.username
photoToUpload["data"] = localDate
//Get bytes size of image
/* var imageSize = Float(imageData!.length)
//Transform into Megabytes
imageSize = imageSize/(1024*1024)
print("Image size is \(imageSize)Mb")
*/
do{
try photoToUpload.save()
} catch _ {
}
print("Successfully Posted.")
let vc = self.storyboard?.instantiateViewControllerWithIdentifier("postController")
self.presentViewController(vc! as UIViewController, animated: true, completion: nil)
}
It seems that you are unwraping an optional value without actualy checking if it is nil.
Probably the issue is from let file: PFFile = PFFile(data: imageData)!. You must check for nil before you unwrap a variable.
I am creating a page view application. I have written code for the ViewController:
import UIKit
class ViewController: UIViewController {
var pageViewController : UIPageViewController!
var pageTitles : NSArray!
var pageImages : NSArray!
#IBAction func restartAction(sender: AnyObject) {}
override func viewDidLoad() {
super.viewDidLoad()
self.pageTitles = NSArray(objects: "This Is Page One!", "This Is Page Two!")
self.pageImages = NSArray(objects: "page1", "page2")
self.pageViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController
self.pageViewController.dataSource = self // <–– Error
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.height - 60)
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func viewControllerAtIndex(index: Int) -> ContentViewController {
if ((self.pageTitles.count == 0) || (index >= self.pageTitles.count)) {
return ContentViewController()
}
let vc : ContentViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ContentViewController") as! ContentViewController
vc.imageFile = self.pageImages[index] as! String
vc.titleText = self.pageTitles[index] as! String
vc.pageIndex = index
return vc
}
func pageViewController(pageViewController: UIPageViewController, viewcontrollerBeforeViewController viewController: UIViewController) ->UIViewController? {
let 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? {
let 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)
}
}
But I am getting an error on this line self.pageViewController.dataSource = self. The error is:
Cannot assign to property: 'self' is immutable
I am unsure of why self is immutable and how to fix it. If someone could please help, thanks in advance.
In swift you'll need to call self.pageViewController.setDelegate(self)
Delegates have been declared as methods, not properties in some cases
I think the compiler is not being very helpful here - try declaring the controller as following datasource protocol and see if that fixes this odd error
class ViewController: UIViewController, UIPageViewControllerDataSource { etc
I'm trying to create a profilePic in a Sign Up View Controller. The profilePic is of type UIImageView. I want to be able to tap it so it instantly pulls up a photo library in an ActionSheet Style. And to also have one of the image box a button to access the camera. Is this possible?
import UIKit
class SignUpViewController: UIViewController, UITextFieldDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// PROFILE PICTURE
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
}
}
Try this code below :
import UIKit
class SignUpViewController: UIViewController, UIImagePickerControllerDelegate {
#IBOutlet weak var profilePic: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "imageTapped:")
profilePic.addGestureRecognizer(tapGesture)
profilePic.userInteractionEnabled = true
}
func imageTapped(gesture:UIGestureRecognizer) {
if let profile1Pic = gesture.view as? UIImageView {
print("Image Tapped")
showActionSheet()
}
}
func camera()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.Camera
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func photoLibrary()
{
var myPickerController = UIImagePickerController()
myPickerController.delegate = self;
myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(myPickerController, animated: true, completion: nil)
}
func showActionSheet() {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.ActionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: UIAlertActionStyle.Default, handler: { (alert:UIAlertAction!) -> Void in
self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(actionSheet, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
profilePic.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
}
Its working on my side..hope will do the some for you !
I recently published a GitHub repository to handle this type of Action Sheet.
You can download this class from here : MSActionSheet
and simply write :
EDIT :
● Now supporting iPad
MSActionSheet(viewController: self, sourceView: sender).showFullActionSheet {
sender.setImage($0, for: .normal)
}
MSActionSheet : is the best library for set user's profile picture.
I used this library but it's not supported in iPad so i
customise for some functions for support to iPad and Display with
popOverController.
Below the step of customisation.
Replace function with showFullActionSheet
func showFullActionSheet(on vc : UIViewController, over btn : UIButton,handler : #escaping (_ : UIImage?) -> Void) {
let sheet = create().addLibrary().addFrontCamera().addRearCamera().addCancelButton()
sheet.show(on: vc,over: btn){ (image : UIImage?) in
handler(image)
}
}
Add code before vc.present(MSActionSheet.sheet!, animated: true, completion: nil) in function show
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
if let presenter = MSActionSheet.sheet?.popoverPresentationController {
presenter.sourceView = btn
presenter.sourceRect = btn.bounds
}
}
Add below code before clientVC?.present(picker, animated: true, completion: nil) in function handler
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.pad {
picker.modalPresentationStyle = .popover
if let presenter = picker.popoverPresentationController {
presenter.sourceView = sourceBtn
presenter.sourceRect = sourceBtn!.bounds
}
}
How to use
let msActionSheet = MSActionSheet.instance
msActionSheet.showFullActionSheet(on: self,over: btn){ (image) in
btn.setImage(image, for: .normal)
}
msActionSheet.tintColor(color: Constants.kColorBluish)
Swift 3x:
class yourClassName:UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBAction func yourButtonName(_ sender: UIButton) {
let pickerView = UIImagePickerController()
pickerView.delegate = self
pickerView.allowsEditing = true
let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: nil, preferredStyle: .actionSheet)
let cancelActionButton: UIAlertAction = UIAlertAction(title: "Cancel", style: .cancel) { action -> Void in
print("Cancel") //Cancel
}
actionSheetControllerIOS8.addAction(cancelActionButton)
let saveActionButton: UIAlertAction = UIAlertAction(title: "Take Photo", style: .default) { action -> Void in
print("Take Photo") //Will open Camera
if UIImagePickerController.isSourceTypeAvailable(.camera) {
pickerView.sourceType = .camera
self.present(pickerView, animated: true, completion: { _ in })
}
}
actionSheetControllerIOS8.addAction(saveActionButton)
let deleteActionButton: UIAlertAction = UIAlertAction(title: "Camera Roll", style: .default) { action -> Void in
print("Camera Roll") //Will open Gallery
pickerView.sourceType = .photoLibrary
self.present(pickerView, animated: true, completion: { _ in })
}
actionSheetControllerIOS8.addAction(deleteActionButton)
let deleteActionButton2: UIAlertAction = UIAlertAction(title: "Import from Facebook", style: .default) { action -> Void in
print("Import from Facebook")
}
actionSheetControllerIOS8.addAction(deleteActionButton2)
self.present(actionSheetControllerIOS8, animated: true, completion: nil)
}
// MARK: - UIImagePickerControllerDelegate Methods
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//print(info)
if let pickedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
//print(pickedImage)
yourImageView.contentMode = .scaleAspectFit
yourImageView.image = pickedImage
}
dismiss(animated: true, completion: nil)
}
}
I have made a statusBar application with a drop down. I would like to open a settingsWindow from that dropdown. I have made the settings window with its own ViewController.
The issue is that i can't figure out how to instantiate and show the settingsWindow that i have made. I have tried to follow every thread on the internet without any success.
My Viewcontroller:
class SettingsViewController: NSViewController {
#IBOutlet var ipAddress: NSTextField!
#IBOutlet var port: NSTextField!
#IBAction func connect(sender: AnyObject) {}
override func viewDidLoad() {
super.viewDidLoad()
}
}
My AppDelegate:
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet var statusMenu: NSMenu!
var statusItem: NSStatusItem?
var tcpService: TcpService = TcpService()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
let bar = NSStatusBar.systemStatusBar()
statusItem = bar.statusItemWithLength(20)
statusItem!.menu = statusMenu
statusItem!.image = NSImage(byReferencingFile: NSBundle.mainBundle().pathForResource("16*16", ofType: "png"))
statusItem!.highlightMode = true
tcpService.initOutputStream("192.168.1.1", Port: 8888)
}
func applicationWillTerminate(aNotification: NSNotification?) {
// Insert code here to tear down your application
}
#IBAction func openSettings(sender: AnyObject) {
// open settings for ip and port optional port
}
}
in swift 3:
var myWindow: NSWindow? = nil
let storyboard = NSStoryboard(name: "Main",bundle: nil)
let controller: EditorViewController = storyboard.instantiateController(withIdentifier: "editorViewController") as! ViewController
myWindow = NSWindow(contentViewController: controller)
myWindow?.makeKeyAndOrderFront(self)
let vc = NSWindowController(window: myWindow)
vc.showWindow(self)
For 2022
in your normal Main storyboard, tap to add a new window controller.
tap precisely on the red "X", then the blue circle, and then enter "ExampleID" at the green entry.
in your app's ordinary main view controller, add this
variable:
var otherWindow: NSWindowController?
function:
private func otherWindow() {
let sb = NSStoryboard(name: "Main", bundle: nil)
otherWindow = sb.instantiateController(
withIdentifier: "ExampleID") as! NSWindowController
otherWindow?.showWindow(self)
}
That's it.
Call otherWindow when you want to.
Problem:
Inevitably you will want to set up the otherWindow in a certain way, example, transparent, whatever. Unfortunately this is a whole topic in itself, but you do it like this:
private func otherWindow() {
... as above ...
otherWindow?.window?.ExampleSetup()
}
and then
extension NSWindow {
func ExampleSetup() {
self.styleMask = .borderless
self.collectionBehavior = [.fullScreenPrimary]
self.level = .floating
self.isMovable = false
self.titleVisibility = .hidden
// etc etc etc ..
guard let screen = self.screen ?? NSScreen.main else {
print("what the???")
return
}
self.setFrame(screen.frame, display: true)
// consider also .visibleFrame
}
}
enum Storyboards: String {
case main = "Main"
func instantiateVC<T>(_ identifier: T.Type) -> T? {
let storyboard = NSStoryboard(name: rawValue, bundle: nil)
guard let viewcontroller = storyboard.instantiateController(withIdentifier: String(describing: identifier)) as? T else { return nil}
return viewcontroller
}
}
var ssoLoginController: IDSSOLoginViewController?
var myWindow: NSWindow? = nil
ssoLoginController = Storyboards.main.instantiateVC(IDSSOLoginViewController.self)
myWindow = NSWindow(contentViewController: ssoLoginController!)
myWindow?.makeKeyAndOrderFront(self)
let vc = NSWindowController(window: myWindow)
vc.showWindow(self)
I am not 100% that I fully understand your problem, but assuming that you are using a storyboard (you should if you are starting fresh), adding few lines to your applicationDidFinishLaunching method will help:
var myWindow: NSWindow? = nil
let storyboard = NSStoryboard(name: "Main",bundle: nil)
let controller: SettingsViewController = storyboard?.instantiateControllerWithIdentifier("SettingsViewController") as SettingsViewController
myWindow = controller.window
myWindow?.makeKeyAndOrderFront(self)
Do not forget to set the Storyboard ID in IB (in the example above to SettingsViewController)!