I have added a swipe gesture in my ios application, but somehow I can't access the camera afterward. I am beginner in swift and I would be very glad if you can advice me how to fix it.
So far I have used:
import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate{
let imagePicker: UIImagePickerController! = UIImagePickerController()
let reachability = Reachability()!
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
self.view.backgroundColor = UIColor.flatBlackColorDark()
let upSwipe = UISwipeGestureRecognizer(target: self, action: Selector(("handleSwipes")))
upSwipe.direction = .up
view.addGestureRecognizer(upSwipe)
}
and for the function:
func handleSwipes(sender:UISwipeGestureRecognizer) {
if (sender.direction == .up){
if ( UIImagePickerController.isSourceTypeAvailable(.camera)){
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
imagePicker.allowsEditing = false
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
present(imagePicker,animated: true, completion: {})
}
}
Where you have:
action: Selector(("handleSwipes"))
put this:
action: #selector(handleSwipes)
The reason is that "handleSwipes" is not the selector for your handleSwipes function, and you do not know how to form the selector correctly. But the compiler does know, and using #selector syntax tells it to do so.
Related
I am making a custom camera in Swift. I declared it global like this:
let image = UIImagePickerController()
I have made OverlayVC (UIViewController) in IB. Made a shutter button and hooked it up like this:
#IBAction func shutterTapped(_ sender: Any) {
print("shutterTapped")
image.takePicture()
}
I instantiate this overlay before presenting:
image.delegate = self
image.sourceType = .camera
image.cameraDevice = .front
image.allowsEditing = false
let overlay = self.storyboard?.instantiateViewController(withIdentifier: "OverlayVC")
image.cameraOverlayView = overlay?.view
image.showsCameraControls = false
self.present(image, animated: true, completion: nil)
Now when I run the build on device and tap on the shutter button, I can visually see it being tapped (fade out/in) but the code in shutterTapped() never executes.
Why is it not really working?
Adding view of the view controller removes controller itself and no one can actually get the event. So, you get the view but not events. and to support this:
Solution that will actually work with your code would be:
image.cameraOverlayView = overlay?.view
if let viewController = overlay {
for view in viewController.view.subviews {
if let button = view as? UIButton {
button.addTarget(self, action: #selector(self.takePicture), for: UIControlEvents.touchDown)
}
}
}
You can also add tag to it so you can check which button is which if you have more of them.
Alternate Solution:
Create UIView subclass and xib for it. Same view you had in the OverlayVC. Then, when adding overlay use following:
image.sourceType = .camera
image.cameraDevice = .front
image.allowsEditing = false
let myOverlay = Bundle.main.loadNibNamed("CameraOverlay", owner: self, options: nil)
image.cameraOverlayView = myOverlay?.first as! UIView
image.showsCameraControls = false
self.present(image, animated: true, completion: nil)
Note that force unwrap should be protected with either guard or if let when casting to UIView.
I'm trying to handle tap gesture in an external UIViewController's class but my function was never called. Here is my
code:
import SceneKit
import UIKit
class SceneManager
{
private let assetFolder: String
private let mainCamera: SCNNode
private let view: SCNView
private let scene: SCNScene
init(view: SCNView, assetFolder: String, sceneFile: String, mainCameraName: String, backgroundColor: UIColor) {
self.assetFolder = assetFolder
self.scene = SCNScene(named: (self.assetFolder + "/scene/" + sceneFile))!
self.mainCamera = self.scene.rootNode.childNodeWithName(mainCameraName, recursively: true)!
self.view = view
self.view.backgroundColor = backgroundColor
self.view.allowsCameraControl = false
self.view.pointOfView = self.mainCamera
self.view.scene = self.scene
//PROBLEM BELOW
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
self.view.addGestureRecognizer(gesture)
}
#objc func handleTap(sender: UITapGestureRecognizer) {
print("hello")
}
}
Here is my ViewController Class :
import UIKit
import QuartzCore
import SceneKit
class ViewController: UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
let view = self.view as! SCNView
view.showsStatistics = true
_ = SceneManager(view: view, assetFolder: "art.scnassets", sceneFile: "EURO_COPTER.dae", mainCameraName: "camera", backgroundColor: UIColor.blackColor())
}
}
If someone has an idea. Thanks in advance.
Try following code it may help
let gesture = UITapGestureRecognizer(target: self, action: #selector(SceneManager.handleTap(_:)))
Try to this way:-
When you declare your class, add UIGestureRecognizerDelegate after the class it subclasses. Here's what that looks like in my case:
let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap(_:)))
self.view.userInteractionEnabled = true;
gesture.delegate = self
self.view.addGestureRecognizer(gesture)
I have recently released my game to the App Store. The iAd banner and medium ads are not showing up after almost a week now. All its showing isa blank space as in the following screenshots.
Can anyone check if there is anything wrong with my iAd code?
Before Release:
After Release:
import UIKit
import SpriteKit
import iAd
import Social
import GameKit
import StoreKit
class GameViewController: UIViewController, ADBannerViewDelegate, GKGameCenterControllerDelegate, ADInterstitialAdDelegate {
var scene: GameScene!
#IBOutlet var bannerView: ADBannerView!
var imageView = UIImageView()
var interAd = ADInterstitialAd()
var mediumRectAdView = ADBannerView(adType: ADAdType.MediumRectangle)
var interAdView = UIView()
var closeButton = UIButton(type: UIButtonType.System)
override func viewDidLoad() {
super.viewDidLoad()
let screenBounds: CGRect = UIScreen.mainScreen().bounds
bannerView = ADBannerView(frame:CGRectMake(0,0,50,screenBounds.width))
bannerView.center = CGPoint(x: screenBounds.width/2, y:screenBounds.height-bannerView.frame.size.height/2)
bannerView.delegate = self
bannerView.hidden = false//false //<<<<<<<<<<<<<<<<<<<<<<,
scene = GameScene(size:CGSize(width: 2048, height: 1536))
let skView = self.view as! SKView
scene.scaleMode = .AspectFill
skView.presentScene(scene)
skView.addSubview(bannerView)
if scene.productPurchased == true {
bannerView.hidden = true
}
firstScene = false
//self.interstitialPresentationPolicy = ADInterstitialPresentationPolicy.Manual
//Authenticate Game Center
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(GameViewController.showAuthenticationViewController),name:PresentAuthenticationViewController, object: nil)
SGGameKit.sharedInstance.authenticateLocalPlayer()
// Share
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.displayShareSheet)), name:mySharePostKey, object: nil)
// Med iAD
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.loadMedAd)), name:myloadMedAdKey, object: nil)
// Interstitial iAD
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.loadInterAd)), name:myloadInterAdKey, object: nil)
// Hide Iad
NSNotificationCenter.defaultCenter().addObserver(self, selector: (#selector(GameViewController.hideAd)), name:myHideAdKey, object: nil)
}
func hideAd() {
print("Hiding Ad")
bannerView.hidden = true
}
func displayShareSheet() {
let initialText = "OMG! I got \(scene.score) points in Jumpox\n" + "https://itunes.apple.com/us/app/id1099659993)"
if let myImage = self.view?.pb_takeSnapshot() {
UIImageWriteToSavedPhotosAlbum(myImage, nil, nil, nil)
let activityViewController = UIActivityViewController(activityItems: [initialText,myImage as UIImage], applicationActivities: [])
activityViewController.excludedActivityTypes = [UIActivityTypeOpenInIBooks]
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Phone {
self.presentViewController(activityViewController, animated: true, completion: {})
}
else {
let popup: UIPopoverController = UIPopoverController(contentViewController:activityViewController)
popup.presentPopoverFromRect(CGRectMake(self.view.frame.size.width / 2, self.view.frame.size.height / 4, 0, 0), inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
}
}
func loadMedAd() {
print("Loading loadMedAd")
closeButton = UIButton(type: UIButtonType.System)
closeButton.frame = CGRectMake(5, 5, 30, 30)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("X", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: #selector(GameViewController.close), forControlEvents: UIControlEvents.TouchDown)
mediumRectAdView!.delegate = self
mediumRectAdView.center = self.view.center
mediumRectAdView.addSubview(closeButton)
interAdView = UIView(frame: self.view.frame)
self.view.addSubview(interAdView)
interAdView.addSubview(mediumRectAdView)
}
func loadInterAd() {
print("Loading loadInterAd")
interAd = ADInterstitialAd()
interAd.delegate = self
//if interAd.loaded {
closeButton.frame = CGRectMake(10, 10, 40, 40)
closeButton.layer.cornerRadius = 10
closeButton.setTitle("X", forState: .Normal)
closeButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
closeButton.backgroundColor = UIColor.whiteColor()
closeButton.layer.borderColor = UIColor.blackColor().CGColor
closeButton.layer.borderWidth = 1
closeButton.addTarget(self, action: #selector(GameViewController.close), forControlEvents: UIControlEvents.TouchDown)
interAdView = UIView(frame: self.view.frame)
interAdView.frame = self.view.bounds
self.view.addSubview(interAdView)
interAd.presentInView(interAdView)
interAdView.addSubview(closeButton)
//}
//requestInterstitialAdPresentation()
}
func interstitialAd(interAd: ADInterstitialAd!, didFailWithError error: NSError!) {
print("Failed To Receive")
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
func close() {
closeButton.removeFromSuperview()
interAdView.removeFromSuperview()
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func showAuthenticationViewController() {
let gameKitHelper = SGGameKit.sharedInstance
if let authenticationViewController = gameKitHelper.authenticationViewController {
self.presentViewController(authenticationViewController, animated: true,
completion: nil)
}
}
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController){
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
iAd has been discontinued and is not accepting new apps into the network.
The iAd App Network will be discontinued as of June 30, 2016. Although
we are no longer accepting new apps into the network, advertising
campaigns may continue to run and you can still earn advertising
revenue until June 30. If you’d like to continue promoting your apps
through iAd until then, you can create a campaign using iAd Workbench.
I'm surprised the reviewer did not reject your submission. Look into AdMob, AppLovin, or the many other ad networks available for iOS.
Depends upon the PlaybackControl Visibity How to show and hide the Custom Subview added in contentOverlayView?
I want to do like Youtube TVOS app did.
I tried with UIPressesEvent but it is not giving me the exact touch events. It is giving me these:
override func pressesBegan(presses: Set<UIPress>, withEvent event: UIPressesEvent?) {
for item in presses {
switch item.type {
case .Menu:
self.customViews.alpha = 0
case .PlayPause:
self.player?.pause()
self.customViews.alpha = 0
default:
self.setVisibilityToPreviewView()
}
}
}
func setVisibilityToPreviewView () { //This wont work in all cases.
if self.previewView.alpha == 1 {
self.previewView.alpha = 0
} else {
self.previewView.alpha = 1
}
}
But with this Touch events i can only show and hide the subviews.
It should be hidden when the playbackcontrol is Hidden.
If I get the PlayBackControl Visibility values I don't need to worry about hiding these subviews.
Apple is Using AVNowPlayingPlaybackControlsViewController. It is not open for developers.
So I need to find some other better way to do this.
Please guide me how to do it.
You can register a tapGesture recognizer and then set its allowPressTypes property to UIPressType.Select, something like this
let tapRecognizer = UITapGestureRecognizer(target: self, action: "onSelect:")
tapRecognizer.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)];
self.view.addGestureRecognizer(tapRecognizer)
And inside your action button show or hide custom overlays.
Example: Add this code inside a view controller and on tap (selecting at empty area on front of remote, touch area) you will see a message on console.
override func viewDidLoad() {
super.viewDidLoad()
let tapGesture = UITapGestureRecognizer(target: self, action: "onSelect")
tapGesture.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
self.view.addGestureRecognizer(tapGesture);
}
func onSelect(){
print("this is select gesture handler method");
}
Update: Below is the code which will create AVPlayerController and will register tapGestureRecognizer to playervc.view.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playContent()
}
func playContent(){
let urlString = "<contentURL>"
guard let url = NSURL(string: urlString) else{
return
}
let avPlayer = AVPlayer(URL: url)
let playerVC = AVPlayerViewController()
playerVC.player = avPlayer
self.playerObj = playerVC
let tapGesture = UITapGestureRecognizer(target: self, action: "onSelect")
tapGesture.allowedPressTypes = [NSNumber(integer: UIPressType.Select.rawValue)]
self.view.addGestureRecognizer(tapGesture);
playerVC.view.addGestureRecognizer(tapGesture)
self.presentViewController(playerVC, animated: true, completion: nil);
}
Give a try to this, I think it should work fine.
I'm having some trouble getting a UIPopover to appear using swift. The code that is commented out works fine in Objective-C, but doesn't work using Swift. When I tap the + in my view controller I do get the "click" in my debugger, however no popover appears.
class PlayerInformationTableViewController: UITableViewController, NSFetchedResultsControllerDelegate, UIPopoverControllerDelegate {
#IBOutlet weak var addBarButtonItem: UIBarButtonItem!
var playerInformationViewController = PlayerInformationViewController()
var popover:UIPopoverController? = nil
override func viewDidLoad() {
super.viewDidLoad()
/*
//setup the popover
_cuesPopoverViewController = [self.storyboard instantiateViewControllerWithIdentifier:#"CuesPopoverViewController"];
self.cuesPopover = [[UIPopoverController alloc] initWithContentViewController:_cuesPopoverViewController];
self.cuesPopover.popoverContentSize = CGSizeMake(540, 300);
self.cuesPopover.delegate = self;
*/
playerInformationViewController.storyboard?.instantiateViewControllerWithIdentifier("PlayerInformationViewController")
popover?.contentViewController = playerInformationViewController
popover?.popoverContentSize = CGSizeMake(300, 300)
popover?.delegate = self
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
#IBAction func addPopover(sender: AnyObject) {
println("Click")
popover?.presentPopoverFromBarButtonItem(addBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
}
Solution
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addPopover(sender: AnyObject) {
var popoverViewController = self.storyboard?.instantiateViewControllerWithIdentifier("PlayerInformationViewController") as UIViewController
popoverViewController.modalPresentationStyle = .Popover
popoverViewController.preferredContentSize = CGSizeMake(450, 450)
let popoverPresentationViewController = popoverViewController.popoverPresentationController
popoverPresentationViewController?.permittedArrowDirections = .Any
popoverPresentationViewController?.delegate = self
popoverPresentationViewController?.barButtonItem = sender as UIBarButtonItem
presentViewController(popoverViewController, animated: true, completion: nil)
}
Here is a simple example for iOS 8. Popover are presented using adaptivity apis in iOS 8.
class PlayerInformationTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate, NSFetchedResultsControllerDelegate{
...
#IBAction func addPopover(sender: UIBarButtonItem){
let playerInformationViewController = PlayerInformationViewController()
playerInformationViewController.modalPresentationStyle = .Popover
playerInformationViewController.preferredContentSize = CGSizeMake(300, 300)
let popoverPresentationViewController = playerInformationViewController.popoverPresentationController
popoverPresentationViewController?.permittedArrowDirections = .Any
popoverPresentationViewController?.delegate = self
popoverPresentationController?.barButtonItem = sender
presentViewController(playerInformationViewController, animated: true, completion: nil)
}
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle{
return .None
}
}
Display Popover with contentView from xib
func showPopover(sender: AnyObject) {
let contentViewController = UINib(nibName: "ContentVC", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as ContentVC
contentViewController.modalPresentationStyle = UIModalPresentationStyle.Popover
var detailPopover: UIPopoverPresentationController = contentViewController.popoverPresentationController!
detailPopover.delegate = self
detailPopover.barButtonItem = sender as UIBarButtonItem
detailPopover.permittedArrowDirections = UIPopoverArrowDirection.Any
presentViewController(contentViewController,
animated: true, completion:nil)
}
Next allows to make not full screen PopoverView on iPhone
for this do not forget to inherit MainViewController: UIPopoverPresentationControllerDelegate and set delegate to PopoverView
func adaptivePresentationStyleForPresentationController(controller: UIPresentationController!) -> UIModalPresentationStyle
{
return .None
}
It looks like your popover is nil. Where are you assigning/instantiating it?
Try changing this:
popover?.presentPopoverFromBarButtonItem(addBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
To this:
if let pop = popover {
pop.presentPopoverFromBarButtonItem(addBarButtonItem, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: true)
} else {
NSLog("Error: Popover was nil")
}
I imagine you'll see that error message in your console. In the .XIB for your PlayerInformationTableViewController, do you have a UIPopoverController?
If so, you probably need to ensure that the var popover is either (1) being manually instantiated in your awakeFromNib, or that it's an #IBOutlet and is being connected properly.
Alternatively, can you simply use the popover already present in your playerInformationViewController?