EventKit in Swift not working with Swift 2.0 - macos

I am trying to migrate to swift 2.0 but not all of my code is working. I have succed to migrate most of the code but I stillt have troubles using the EventKit. The code below was working fine with swift 1.2. But now I have a Problem
import Foundation
import EventKit
import Cocoa
private let _SingletonSharedInstance = EventStore()
class EventStore {
let eventStore = EKEventStore ()
class var sharedInstance : EventStore {
return _SingletonSharedInstance
}
init() {
var sema = dispatch_semaphore_create(0)
var hasAccess = false
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted:Bool, error:NSError?) in hasAccess = granted; dispatch_semaphore_signal(sema) })
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
if (!hasAccess) {
println("ACCESS", "ACCESS LONG")
let sharedWorkspace = NSWorkspace.sharedWorkspace()
sharedWorkspace.openFile("/Applications/System Preferences.app")
exit (0)
}
}
}
Following line is causing the Problems
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { (granted:Bool, error:NSError?) in hasAccess = granted; dispatch_semaphore_signal(sema) })
I am getting the error
cannot invoke "requestAccessToEntityType" with an argument list of type '(EKEEntityType, completion: (Bool, NSError?) -> ())'
I read that using NSError! should solve the issue but it did not.
Any ideas?

I found the answer. The bool type had changed to ObjCBool and EKEntityTypeEvent to EKEntityType.Event.
import Foundation
import EventKit
import Cocoa
private let _SingletonSharedInstance = EventStore()
class EventStore {
let eventStore = EKEventStore ()
class var sharedInstance : EventStore {
return _SingletonSharedInstance
}
init() {
var sema = dispatch_semaphore_create(0)
var hasAccess:ObjCBool = false
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: { (granted:ObjCBool, error:NSError?) in hasAccess = granted; dispatch_semaphore_signal(sema) })
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER)
if (!hasAccess) {
println("ACCESS", "ACCESS LONG")
let sharedWorkspace = NSWorkspace.sharedWorkspace()
sharedWorkspace.openFile("/Applications/System Preferences.app")
exit (0)
}
}
}

Related

Implementing AdMob Interstitial Ads in SwiftUI (5) and Xcode (12.4)

I am working on implementing Interstitial ads in my app and running into some confusion with the docs provided by Admob and the new SwiftUI app structure.
Here is the app.swift file, showing that I've implemented the GoogleMobileAds and started it in the didFinishLaunchingWithOptions method.
import SwiftUI
import GoogleMobileAds
#main
struct adamsCalcApp: App {
var calculator = Calculator()
#UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView().environmentObject(calculator)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Setup google admob instance
GADMobileAds.sharedInstance().start(completionHandler: nil)
return true
}
}
In my ContentView.swift File, I have the interstitial variable created like...
#State var interstitial: GADInterstitialAd?
Then on the main stack in the view, I call onAppear(perform: ) to load the ad, however I keep getting this error.
.onAppear(perform: {
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/4411468910",
request: request,
completionHandler: { [self] ad, error in
if let error = error {
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
}
)
})
"Cannot assign value of type 'ContentView' to type
'GADFullScreenContentDelegate?'"
I am feeling a bit clueless after trying a few different workarounds and trying to look up a setup that is like mine, AdMob docs still show how to implement with class ViewControllers and I would like to figure out how to do this is SwiftUI.
import SwiftUI
import GoogleMobileAds
import AppTrackingTransparency
import AdSupport
class AdsManager: NSObject, ObservableObject {
private struct AdMobConstant {
static let interstitial1ID = "..."
}
final class Interstitial: NSObject, GADFullScreenContentDelegate, ObservableObject {
private var interstitial: GADInterstitialAd?
override init() {
super.init()
requestInterstitialAds()
}
func requestInterstitialAds() {
let request = GADRequest()
request.scene = UIApplication.shared.connectedScenes.first as? UIWindowScene
ATTrackingManager.requestTrackingAuthorization(completionHandler: { status in
GADInterstitialAd.load(withAdUnitID: AdMobConstant.interstitial1ID, request: request, completionHandler: { [self] ad, error in
if let error = error {
print("Failed to load interstitial ad with error: \(error.localizedDescription)")
return
}
interstitial = ad
interstitial?.fullScreenContentDelegate = self
})
})
}
func showAd() {
let root = UIApplication.shared.windows.last?.rootViewController
if let fullScreenAds = interstitial {
fullScreenAds.present(fromRootViewController: root!)
} else {
print("not ready")
}
}
}
}
class AdsViewModel: ObservableObject {
static let shared = AdsViewModel()
#Published var interstitial = AdsManager.Interstitial()
#Published var showInterstitial = false {
didSet {
if showInterstitial {
interstitial.showAd()
showInterstitial = false
} else {
interstitial.requestInterstitialAds()
}
}
}
}
#main
struct YourApp: App {
let adsVM = AdsViewModel.shared
init() {
GADMobileAds.sharedInstance().start(completionHandler: nil)
}
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(adsVM)
}
}
Toggle the showInterstitial parameter in the AdsViewModel anywhere in the application and the advertisement will be shown.
In order to use the Admob docs with the newest SwiftUI release, you need to change this line...
.onAppear(perform: {
let request = GADRequest()
GADInterstitialAd.load(withAdUnitID:"ca-app-pub-3940256099942544/4411468910",
request: request,
completionHandler: { [self] ad, error in
if let error = error {
return
}
// Change these two lines of code
interstitial = ad
interstitial?.fullScreenContentDelegate = self
// To...
interstitial = ad
let root = UIApplication.shared.windows.first?.rootViewController
self.interstitial!.present(fromRootViewController: root!)
}
)
})

applicationDidFinishLaunching not invoked on Console App

I'm trying to write a simple command line app that can display some info on a notification. But, the Delegate is not being called, and neither is the Notification and I'm not sure what's missing here.
Judging from my output, I think the whole problem stems from the AppDelegate not being instantiated. But I am creating one just before I show call showNotification.
What am I missing here?
src/main.swift
import Foundation
import AppKit
var sema = DispatchSemaphore( value: 0 )
let server: String = "http://jsonip.com"
let port: String = "80"
let path: String = "/"
let todoEndpoint: String = server + ":" + port + path
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
let url = URL(string: todoEndpoint)!
let task = session.dataTask(with: url, completionHandler: {
(data, response, error) in
if error != nil {
print(error!.localizedDescription)
} else {
do {
if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
{
print(json)
let ad = AppDelegate()
ad.showNotification(title: "Title", subtitle: "SubTitle", informativeText: String(describing: json))
sema.signal()
}
} catch {
print("error in JSONSerialization")
}
}
})
print("Resume Task")
task.resume()
print("Wait for Semaphore")
sema.wait()
src/AppDelegate.swift
import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
func applicationDidFinishLaunching(aNotification: Notification) {
NSUserNotificationCenter.default.delegate = self
print("Delegate Self")
}
// NSUserNotificationCenterDelegate implementation
private func userNotificationCenter(center: NSUserNotificationCenter!, didDeliverNotification notification: NSUserNotification!) {
//implementation
}
private func userNotificationCenter(center: NSUserNotificationCenter!, didActivateNotification notification: NSUserNotification!) {
//implementation
}
private func userNotificationCenter(center: NSUserNotificationCenter!, shouldPresentNotification notification: NSUserNotification!) -> Bool {
//implementation
return true
}
func showNotification(title: String, subtitle: String, informativeText: String) -> Void {
let notification: NSUserNotification = NSUserNotification()
print("Show Notification")
notification.title = title
notification.subtitle = subtitle
notification.informativeText = informativeText
//notification.contentImage = contentImage
notification.soundName = NSUserNotificationDefaultSoundName
NSUserNotificationCenter.default.deliver(notification)
print(notification.isPresented)
}
}
Output
Resume Task
Wait for Semaphore
["about": /about, "reject-fascism":
Impeach Trump!, "ip": 110.50.73.141, "Pro!": http://getjsonip.com]
Show Notification
false
Program ended with exit code: 0

Depreciated Code from Swift 2 to Swift 3

So I followed this tutorial on youtube: https://www.youtube.com/watch?v=uUTevJAhL3Q, and I can't figure out how to update the rest to Swift 3; I am relatively new at Swift and still learning, if anyone could help me out a bit that would be fantastic! I am trying to re-create a snapchat camera-view.
import UIKit
import AVFoundation
class CameraVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?
#IBOutlet var cameraView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
previewLayer?.frame = cameraView.bounds
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
captureSession = AVCaptureSession()
captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080
var backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
if (error == nil && captureSession?.canAddInput(input) != nil){
captureSession?.addInput(input)
stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]
if (captureSession?.canAddOutput(stillImageOutput) != nil){
captureSession?.addOutput(stillImageOutput)
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
cameraView.layer.addSublayer(previewLayer!)
captureSession?.startRunning()
}
}
}
#IBOutlet var tempImageView: UIImageView!
func didPressTakePhoto(){
if let videoConnection = stillImageOutput?.connection(withMediaType: AVMediaTypeVideo){
videoConnection.videoOrientation = AVCaptureVideoOrientation.portrait
stillImageOutput?.captureStillImageAsynchronously(from: videoConnection, completionHandler: {
(sampleBuffer, error) in
if sampleBuffer != nil {
var imageData = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(sampleBuffer)
var dataProvider = CGDataProvider(data: imageData as! CFData)
var cgImageRef = CGImage(jpegDataProviderSource: dataProvider, decode: nil, shouldInterpolate: true, intent: kCGRenderingIntentDefault)
var image = UIImage(CGImage: cgImageRef, scale: 1.0, orientation: UIImageOrientation.Right)
self.tempImageView.image = image
self.tempImageView.isHidden = false
}
})
}
}
var didTakePhoto = Bool()
func didPressTakeAnother(){
if didTakePhoto == true{
tempImageView.isHidden = true
didTakePhoto = false
}
else{
captureSession?.startRunning()
didTakePhoto = true
didPressTakePhoto()
}
}
func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
didPressTakeAnother()
}
}
Swift 3 introduced the idea of error handling and most (if not all) of Apple's Foundation and Core APIs got updated so that instead of using capturing an error with the inout &error parameter the method throws and error.
So code that you used to write like this:
var error : NSError?
var input = AVCaptureDeviceInput(device: backCamera, error: &error)
In Swift 3 is updated to drop the error parameter, and you use the new do, try, catch syntax:
do {
var input = try AVCaptureDeviceInput(device: backCamera)
//... input was assigned without an error, you can use in the scope of this statement
}
catch {
// an error occured attempting `AVCaptureDeviceInput(device: backCamera)`
print("an error occured")
}
Of if you prefer, the shorthand versions:
var input = try! AVCaptureDeviceInput(device: backCamera)
// not safe: app will crash if AVCaptureDeviceInput fails
var input = try? AVCaptureDeviceInput(device: backCamera)
// safer: input will be assigned as `nil` if AVCaptureDeviceInput fails
Next time you're converting from Swift 2 to Swift 3, try using Xcode's 'refactor' tool it does a pretty good job of automatically making these changes for you.

Can't see banner for iAds

Does any body else have the problem were they can't see the banner for iAds but when you first run the app a big blue screen shows up and says your now connected to iAds. I'm running my app an my iPhone and my iAD developer app testing fill rate is set to 100%
Code:
import UIKit
import StoreKit
import SpriteKit
import GameKit
import iAd
extension SKNode {
class func unarchiveFromFile(file : String) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
class GameViewController: UIViewController, ADInterstitialAdDelegate {
var interstitialAd:ADInterstitialAd!
var interstitialAdView: UIView = UIView()
override func viewDidLoad() {
super.viewDidLoad()
loadInterstitialAd()
ADBannerView()
func gameCenterViewControllerDidFinish(gameCenterViewController: GKGameCenterViewController!)
{
gameCenterViewController.dismissViewControllerAnimated(true, completion: nil)
}
var localPlayer = GKLocalPlayer()
localPlayer.authenticateHandler = {(viewController, error) -> Void in
if (viewController != nil) {
let vc: UIViewController = self.view!.window!.rootViewController!
vc.presentViewController(viewController, animated: true, completion: nil)
}
else {
println((GKLocalPlayer.localPlayer().authenticated))
}
}
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = false
skView.showsNodeCount = false
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
func loadInterstitialAd() {
interstitialAd = ADInterstitialAd()
interstitialAd.delegate = self
}
func interstitialAdWillLoad(interstitialAd: ADInterstitialAd!) {
}
func interstitialAdDidLoad(interstitialAd: ADInterstitialAd!) {
interstitialAdView = UIView()
interstitialAdView.frame = self.view.bounds
view.addSubview(interstitialAdView)
interstitialAd.presentInView(interstitialAdView)
UIViewController.prepareInterstitialAds()
}
func interstitialAdActionDidFinish(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
func interstitialAdActionShouldBegin(interstitialAd: ADInterstitialAd!, willLeaveApplication willLeave: Bool) -> Bool {
return true
}
func interstitialAd(interstitialAd: ADInterstitialAd!, didFailWithError error: NSError!) {
}
func interstitialAdDidUnload(interstitialAd: ADInterstitialAd!) {
interstitialAdView.removeFromSuperview()
}
}

SKStoreProductViewController not showing up in swift (in-app purchases)

I am trying to add in-app purchases to my iOS app. I followed a tutorial and I created the following code:
import UIKit
import StoreKit
let secondViewController: SKStoreProductViewController = SKStoreProductViewController();
class GameViewController: UIViewController, UITextFieldDelegate, GKGameCenterControllerDelegate, SKStoreProductViewControllerDelegate{
func buycoin(){
println("buycoin")
secondViewController.delegate = self
var someitunesid:String = "coin200a"
var productparameters = [SKStoreProductParameterITunesItemIdentifier: someitunesid]
secondViewController.loadProductWithParameters(productparameters, {
(success:Bool!, error: NSError!) -> Void in
if success == true{
self.presentViewController(secondViewController, animated: true, completion: nil)
println("succes")
}
else{
NSLog("%#", error)
println("nosucces")
}
})
}
func productViewControllerDidFinish(viewController: SKStoreProductViewController!) {
secondViewController.dismissViewControllerAnimated(true, completion: nil)
}
}
This code works fine. When the function buycoin() activates, I only get printed buycoin in the console, nothing else.
What am I doing wrong?

Resources