I've made a game using SpriteBuilder and it's written in Swift. I'd like to add advertisements before I ship an update to the App Store. Can someone please help me with how to do this?
To add iAd to your game, you need to add the iAd framework to your app (via Build Phases) and add the import statement import iAd in the class that handles your iAd implementation.
The simplest iAd ad to add to your Swift game is a banner ad:
override func viewDidLoad() {
super.viewDidLoad()
self.canDisplayBannerAds = true
}
Make sure to import iAd and add the AdBannerViewDelegate protocol to your class declaration:
import iAd
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate,ADBannerViewDelegate
Then you need to create the actual banner view, set the delegate (in ViewDidLoad) and add two delegate methods, so that you know when to add/remove the advertisement banner from the view:
bannerViewDidLoadAd:
bannerView:didFailToReceiveAdWithError:
It's fairly easy.
1) Import the iAd framework >Build Phases> Link Binary With Libraries> find iAd
2) drag an iAd BannerView from the object library
3) Make an outlet connecting the iAd BannerView to your VC file
4) Add the delegate to your VC class
import iAd
class ViewController: UIViewController, ADBannerViewDelegate{
#IBOutlet var adBannerView: ADBannerView?
override func viewDidLoad(){
self.canDisplayBannerAds = true
self.ADBannerView?.delegate = self
self.ADBannerView.hidden = true
}
func bannerViewWillLoadAd(banner: AdBannerView!){ // any addition set up you want
}
func bannerViewDidLoadAd(banner: ADBannerView!){
self.ADBannerView?.hidden = false
}
func bannerViewActionDidFinish(banner: ADBannerView!){// any addition set up you want
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Boll) -> Bool {
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!){
self.adBannerView?.hidden = false
}
}
Of course you'll have to adjust to display when ever and where you wan it.
Related
For some reason, the WKWebView just shows a blank screen with no errors
import Cocoa
import WebKit
class ViewController: NSViewController, WKNavigationDelegate {
#IBOutlet weak var webView: WKWebView?
override func viewDidLoad() {
super.viewDidLoad()
webView?.navigationDelegate = self
let url=URL(string: "https://www.google.com")
webView?.load(URLRequest(url: url!))
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
}
Like I said, no errors, and it just shows a blank screen.
The storyboard looks like this:
Main.storyboard
You need to allow your application to have outgoing connections.
In your Target go to Capabilities, enable the App SandBox and check the Outgoing Connections.
Trying to setup validation for a few text fields in a new (and very small) Swift Mac app. Following various other topics here on SO and a few other examples, I can still not get controlTextDidChange to propagate (to my ViewController).
E.g: How to live check a NSTextField - Swift OS X
I have read at least a dozen variations of basically that same concept. Since none of the accepted answers seem to work I am just getting more and more confused by something which is generally a fairly simple task on most platforms.
I have controlTextDidChange implemented to just call NSLog to let me know if I get anything.
AppDelegate should be part of the responder chain and should eventually handle controlTextDidChange but I see nothing there either.
Using the current Xcode I start a new project. Cocoa app, Swift, Storyboard and nothing else.
From what I can gather the below isolated example should work. In my actual app I have tried some ways of inserting the ViewController into the responder chain. Some answers I found suggested it was not always there. I also tried manually adding the ViewController as the delegate in code theTextField.delegate = self
Nothing I have done seems to get text changed to trigger any events.
Any ideas why I have so much trouble setting up this delegation?
My single textfield example app
Storyboard is about as simple as it gets:
AppDelegate
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTextFieldDelegate, NSTextDelegate {
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func controlTextDidChange(notification: NSNotification) {
let object = notification.object as! NSTextField
NSLog("AppDelegate::controlTextDidChange")
NSLog("field contains: \(object.stringValue)")
}
}
ViewController
import Cocoa
class ViewController: NSViewController, NSTextFieldDelegate, NSTextDelegate {
#IBOutlet var theTextField: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
func controlTextDidChange(notification: NSNotification) {
let object = notification.object as! NSTextField
NSLog("ViewController::controlTextDidChange")
NSLog("field contains: \(object.stringValue)")
}
}
I think the samples you're following are a bit out-of-date.
Try...
override func controlTextDidChange(_ notification: Notification) {
...as the function definition for your method in your NSTextFieldDelegate.
I am trying to add a interstitial ad in a Swift SpriteKit game and most of the problems/soultions I see are related to the banner view and not the interstitial display of the admob ads.
What I did was adding all the frameworks and the sample code from google like described here Adding interstitial ads to your project into my GamveViewController.swift
import UIKit
import GoogleMobileAds
class ViewController: UIViewController {
var interstitial: GADInterstitial!
override func viewDidLoad() {
super.viewDidLoad()
interstitial = GADInterstitial(adUnitID: "ca-app-pub-3940256099942544/4411468910")
let request = GADRequest()
// Requests test ads on test devices.
request.testDevices = ["2077ef9a63d2b398840261c8221a0c9b"]
interstitial.loadRequest(request)
}
}
Then I want to call the function to display the ad in my GameScene.swift and this leads to an error and I dont know why
if (self.interstitialAd.isReady) {
self.interstitialAd.presentFromRootViewController(self)
}
The error codes I get are:
1. "use of undeclared type "GADInerstittial"
2."GameScene has no member interstitial
It seems I need to connect my GameViewController and the Game Scene, but I do not know how. Anyone with a helping hand?
You cannot just present the ad in a gameScene, you need a viewController.
The easiest way is to put the code from GameScene into your ViewController.
So move/or create a func in ViewController like so
func showInterAd() {
/// code to present inter ad
}
Than you can use something like NSNotificationCenter to forward the message from GameScene to the ViewController.
Still in your ViewController add an observer in viewDidLoad
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(showInterAd), name: "ShowAd", object: nil)
Than in your GameScene when you want to show the ad post the notification.
NSNotificationCenter.defaultCenter().postNotificationName("ShowAd", object: nil)
Alternatively I have a helper on gitHub if you want a cleaner and more reusable solution
https://github.com/crashoverride777/Swift-iAds-AdMob-CustomAds-Helper
I have very little knowledge about Swift, xCode or Objective-C but I have read/watch a lot of tutorials and my only intention is to create a webview with notification in webkit wrapper such as this Cocoa application provided by xCode.
Currently I have my code that can pretty much run when I build it.
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://irccloud.com"
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
}
override func webView(sender: WebView!, runJavaScriptAlertPanelWithMessage message: String!, initiatedByFrame frame: WebFrame!) {
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Now, if I access irccloud url directly I'm able to receive both sound and banner notification, but I'm wondering how can I make this notification able to display like native Mac app written in Swift?
This app able to do that, but it's in Objective-C https://github.com/jnordberg/irccloudapp
I tried to implement ADBannerView with the old way like Objective C but unsuccessfull. Everythings work but the advertisments didn't show up, it stays a blank field.
func bannerViewDidLoadAd(banner: ADBannerView!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
banner.alpha = 1
UIView.commitAnimations()
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(1)
banner.alpha = 0
UIView.commitAnimations()
}
Anyone who already tried iAd on Swift?
I've found a solution, how to implement it. (You can use inside each method "banner.alpha 1.0" or other things, too.)
//import ... your normal imports as UIKit etc.
import iAd
class YourClassViewController: UIViewController, ADBannerViewDelegate {
#IBOutlet var adBannerView: ADBannerView //connect in IB connection inspector with your ADBannerView
override func viewDidLoad() {
super.viewDidLoad()
self.canDisplayBannerAds = true
self.adBannerView.delegate = self
self.adBannerView.hidden = true //hide until ad loaded
}
func bannerViewWillLoadAd(banner: ADBannerView!) {
NSLog("bannerViewWillLoadAd")
}
func bannerViewDidLoadAd(banner: ADBannerView!) {
NSLog("bannerViewDidLoadAd")
self.adBannerView.hidden = false //now show banner as ad is loaded
}
func bannerViewActionDidFinish(banner: ADBannerView!) {
NSLog("bannerViewDidLoadAd")
//optional resume paused game code
}
func bannerViewActionShouldBegin(banner: ADBannerView!, willLeaveApplication willLeave: Bool) -> Bool {
NSLog("bannerViewActionShouldBegin")
//optional pause game code
return true
}
func bannerView(banner: ADBannerView!, didFailToReceiveAdWithError error: NSError!) {
NSLog("bannerView")
}
//... your class implementation code
}
See the following answer, on how to do it without IBBuilder!
If you are using iOS 7, extension methods and properties have been added to UIViewController to support handling of iAd:
See
https://developer.apple.com/library/prerelease/ios/documentation/iAd/Reference/UIViewController_iAd_Additions/index.html
To show an iAd you first need to add the iAd framework, go to the projects properties, general tab, add the iAd.framework in the Linked framework and libraries section.
In your view controller, import iAd to access the iAd extensions. And finally in viewDidLoad, set self.canDisplayBannerAds = true.
To remove ads, set canDisplayBannerAds to false
Note there is no need to create an AdBannerView in the story board or programmatically and there is no need for your view controller to implement the AdViewDelegate.
import UIKit
import iAd
class ViewController : UIViewController
{
override func viewDidLoad()
{
super.viewDidLoad()
//That's it
self.canDisplayBannerAds = true
}
}
Mr. T answer contains a lot of useless code.
All you need is this part to show ads in your controller:
override func viewDidLoad() {
super.viewDidLoad()
canDisplayBannerAds = true
}
And when you don't need ads, you canDisplayBannerAds = false.
What it does — wrapping your controller into another controller with ad banner at the bottom. This feature is available since iOS7.
It's not possible to get delegate messages with it, so if you need it — you should replace it with ADBannerView instance variable.