Calling delegate methods for Chartboost in IOS Swift - ios

I've integrated Chartboost into my app and I am able to see ads, but I don't have a firm grasp of delegates and I am having trouble using the Chartboost provided code to cause actions to occur after an ad is viewed. My app delegate code is below (i replaced the actual appid and signature that I'm using):
class AppDelegate: UIResponder, UIApplicationDelegate, ChartboostDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
application.isStatusBarHidden = true
Chartboost.start(withAppId: "appID", appSignature: "appSignature", delegate: self)
Chartboost.cacheRewardedVideo(CBLocationHomeScreen)
Chartboost.cacheInterstitial(CBLocationHomeScreen)
func didDisplayInterstitial(_ location: String!){print("didDisplayI")}
func didCloseInterstitial(_ location: String!){print("didCloseI")}
func didDismissInterstitial(_ location: String!){print("didDismissI")}
return true
}
Then in my ViewController I have the following:
class CharacterCreationViewController: UIViewController, ChartboostDelegate {
weak var delegate: ChartboostDelegate?
Override func viewDidLoad() {
super.viewDidLoad()
Chartboost.setDelegate(self)
}
#IBAction func watchAd(_ sender: Any) {
Chartboost.showInterstitial(CBLocationLevelStart)
delegate?.didDismissInterstitial!(CBLocationLevelStart)
delegate?.didCloseInterstitial!(CBLocationLevelStart)
delegate?.didDisplayInterstitial!(CBLocationLevelStart)
}
The watchAd function is a button, and when I press it the ad runs, but none of the actions in the appDelegate file run once the ad is completed/dismissed/closed.
I've searched StackOverflow and the Chartboost help sections and messaged Chartboost support but I'm struggling to find where I've gone wrong.

Related

xmppStreamDidConnect never gets called in Swift

I am trying to connect to my chat server in a Swift app using XMPPFramework, but the didConnect delegate method never gets called.
I have created a basic app in Objective C and I can connect and authenticate in my chat sever without problems.
In the Swift project I tried to connect with the code:
class AppDelegate: UIResponder, UIApplicationDelegate {
var stream:XMPPStream = XMPPStream()
var reconnect:XMPPReconnect = XMPPReconnect()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
stream.addDelegate(self, delegateQueue: DispatchQueue.main)
stream.myJID = XMPPJID(string: "user#chatserver.net")
reconnect.activate(stream)
do {
try stream.connect(withTimeout: XMPPStreamTimeoutNone)
}
catch let err{
print("error occured in connecting\(String(describing: err.localizedDescription))")
}
return true
}
I’ve debugged XMPPFramework and in the method - (void)handleStreamFeatures a call to the delegate is executed :
[multicastDelegate xmppStreamDidConnect:self];
I’ve watched the multicastDelegateObject and has a node with reference to my delegate, and to OS_dispatch_queue_main, but after execution my xmppStreamDidConnect method isn’t executed.
As it is described in this Github Issue, the problem was the method declaration.
My xmppStreamDidConnect need an underscore, the root problem was that if you don't import the swift extensions the compiler marks that declaration as incorrect, although it works.
So to fix my problem, I need to import the pod 'XMPPFramework/Swift' and change the method declaration to
func xmppStreamDidConnect(_ sender: XMPPStream) {

AVCaptureDevice.requestAccess presents unexpected behavior with a UINavigationController

Working with Xcode 10.1 and Swift 4.2
I have a complex app that uses a UINavigationController implemented in the AppDelegate.
The rootViewController of the navigationController is a DashboardController() class (subclass of UIViewController)
The DashboardController implements a left menu drawer using several ViewControllers (with self.addChild(viewController))
Everything works fine, except when I need to push a viewController to present a BarCodeScannerView().
The barebone barCodeScannerView can be pushed and popped as expected.
The problems arises when I request access to the camera (only the first time).
As soon as I present the Device.requestAccess(for:) as follow: the viewController is popped and the previous view (rootViewController) is presented. (Still with the "App would like to access the camera" AlertView)
func requestCameraAccess() {
AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
if granted {
self.launchScanner()
} else {
self.goBack()
}
}
}
If I click "OK" The system will register that the access was granted, but the
applicationDidBecomeActive (in the AppDelegate) is called after aprox 1 second. I have some initializers in applicationDidBecomeActive, and they all are executed again. And after a quick delay, everything works fine.
BTW: applicationWillResignActive, applicationDidEnterBackground and applicationWillEnterForeground are NOT called. So it is clear that this is not part of an App LifeCycle.
Any idea what might me going on here? What can make the system call applicationDidBecomeActive within the app? and still keep everything running?
Thx in advance...
UPDATE After reading the comments, I was able to isolate the issue #2 as follows:
A simple/barebones project with a UINavigationController with a dashboardViewController as rootViewController. The dashboardViewController pushes a CameraViewController() in viewDidLoad(). The cameraViewController requests access to the camera. When clicking OK, the call to applicationDidBecomeActive is triggered.
The full project is attached. (except the "Privacy - Camera Usage Description" key in the .plist.
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow? = UIWindow()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let dashboardViewController = DashboardViewController()
window?.rootViewController = UINavigationController(rootViewController: dashboardViewController)
window?.makeKeyAndVisible()
return true
}
func applicationDidBecomeActive(_ application: UIApplication) {
print("applicationDidBecomeActive")
}
func applicationWillResignActive(_ application: UIApplication) {}
func applicationDidEnterBackground(_ application: UIApplication) {}
func applicationWillEnterForeground(_ application: UIApplication) {}
func applicationWillTerminate(_ application: UIApplication) {}
}
class DashboardViewController: UIViewController {
override func viewDidAppear(_ animated: Bool) {
let cameraVC = CameraViewController()
self.navigationController?.pushViewController(cameraVC, animated: true)
}
}
import AVFoundation
class CameraViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
AVCaptureDevice.requestAccess(for: AVMediaType.video) { granted in
if granted {
print("Access granted")
}
}
}
}
I'd say the problem is just with your testing procedure. When I run your code with a print statement in applicationWillResignActive, this is what I see:
applicationDidBecomeActive
applicationWillResignActive
Access granted
applicationDidBecomeActive
That seems completely in order and normal. It would have been weird to get a spurious didBecomeActive, but that is not what's happening; we resign active and then become active again, which is fine. You should expect that at any time your app can resign active and become active again. Many things in the normal lifecycle can cause that, and the presentation of an out-of-process dialog like the authorization dialog can reasonably be one of them. You should write your code in such a way as to cope with that possibility.

IOS AppDelegate Variable in controller or token

im totally {fresh/beginner} app developer please bear with me if im asking any stupid question.
I trying to show token on my story board when my app runs. if you check my code. i already created delegates variable var tokenVal = "" when i run the app i do not get any value on my story board although, its printing token in console.
2nd issue its showing warnings although its compiling and running.
here is my problem AppDelegate.swift code
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var tokenVal = ""
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
registerPushNotifications()
return true
}
func registerPushNotifications() {
DispatchQueue.main.async {
let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: nil)
UIApplication.shared.registerUserNotificationSettings(settings)
}
}
func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
if notificationSettings.types != UIUserNotificationType() {
application.registerForRemoteNotifications()
}
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
var token = ""
for i in 0..<deviceToken.count {
token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
}
tokenVal = token
print(token)
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Registration failed!")
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
ViewController.swift Code
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var TokenLb: UILabel!
#IBOutlet weak var tokenVarVal: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let appDelegate = UIApplication.shared.delegate as! AppDelegate
//let aVariable = appDelegate.
let bVariable = appDelegate.tokenVal
tokenVarVal.text = bVariable
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
It's a simple matter of the order of operations. The app delegate's tokenVal is being set after the view controller's viewDidLoad runs.
(In general, using one class's property as a "drop" for another class to pick up a value later on is a clumsy strategy. If the other class needs this value, give the value to the other class.)

Chartboost delegate error

I am integrating chartboost into my sprite kit game and have successfully integrated bridging files into my swift code. Now in my app delegate I have the following:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let kChartboostAppID = "5554c8680d60255c6a0f4af4"
let kChartboostAppSignature = "1d0e271cd054c9a63473d2f1212ca33a2922a19f"
Chartboost.startWithAppId(kChartboostAppID, appSignature: kChartboostAppSignature, delegate: self)
Chartboost.cacheMoreApps(CBLocationHomeScreen)
return true
}
class func showChartboostAds()
{
Chartboost.showInterstitial(CBLocationHomeScreen);
}
func didFailToLoadInterstitial(location: String!, withError error: CBLoadError) {
}
the startWithId line gives me an error that it cant invoke this method with these arguments ( String, String, AppDelegate). This used to work fine on my objective c code.. Anyone knows how to fix this?
class AppDelegate: UIResponder, UIApplicationDelegate, ChartboostDelegate
Edit (from Lalit's comment below)
In startWithAppId the delegate is set to self, so you have to set the class AppDelegate as the delegate, which is done using:
ChartboostDelegate(protocol)

IOS Swift and Facebook SDK

Let me apologize first, just learning swift, so I am not 100% on what I am doing. I have found many tutorials on integrating a facebook login in swift and have what appears to be working in the app, but it seems my delegates are never getting called. What I expect to happen is when a user logins 2 things should happen.
1) The login button for facebook should change to a logout button.
2) A console command should print that I logged in, and ultimately user information.
ViewController Class is:
class ViewController: UIViewController,FBLoginViewDelegate {
#IBOutlet var fbLoginView : FBLoginView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.fbLoginView.delegate = self
self.fbLoginView.readPermissions = ["public_profile", "email", "user_friends"]
}
// Facebook Delegate Methods
func loginViewShowingLoggedInUser(loginView : FBLoginView!) {
println("User Logged In")
println("This is where you perform a segue.")
}
func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser){
println("User Name: \(user.name)")
}
func loginViewShowingLoggedOutUser(loginView : FBLoginView!) {
println("User Logged Out")
}
func loginView(loginView : FBLoginView!, handleError:NSError) {
println("Error: \(handleError.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
AppDelegate sections are:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
FBLoginView.self
FBProfilePictureView.self
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
var wasHandled:Bool = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
return wasHandled
}
return true
}
As you can see, most of this is straight from the tutorials but is not working correctly. I've got my info.plist configured, and the FBLoginView appears and goes thru the entire authentication, but nothing is printed to console and the button doesn't change. When I try to click it again, I get app already authorized, which should mean that the auth was successful, but nothing got triggered back in my app.
I feel confident that something is probably wrong with my appdelegate but being new to swift, I have no clue what..
Facebook as changed SDk. Please find the latest solution here
http://www.brianjcoleman.com/tutorial-how-to-use-login-in-facebook-sdk-4-0-for-swift/
I would like to suggest you the cheking of these steps:
-in your VC class, import FacebookSDK statement and FBLoginViewDelegate ?
- your outlet should be:
//FB outlet
#IBOutlet var fbLoginView: FBLoginView
- in your AppDelegate.swift, also imported the FacebookSDK ?
- you have a func in a func in your AppDelegate.swift.It should be:
import FacebookSDK
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
//FB implementation
FBLoginView.self
FBProfilePictureView.self
return true
}
//FB Method handles what happens after authentication
func application (application:UIApplication, openURL url:NSURL, sourceApplication:NSString?, annotation:AnyObject) -> Bool {
//test var
var wasHandled:Bool = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
// attempt to extract a token from the url
return wasHandled
}

Resources