I've a venerable app that I've coerced from the Apple example code GLEssentials in obj-c to Swift 2 and now I'm trying to move to Swift 3. It has a NSOpenGLView at it's core, the main renderer is still not in Swift (I know: I'll have to bite the bullet soon and migrate to Metal or suchlike), but everything else is.
Currently in OSX 10.12, with Xcode 8 the window is just blank. I've had to make some compiler-suggested changes to the main (Swift) OpenGLView class to get it to compile and run succesfully in Swift 3, and I feel this is where the problem lies as the renderer class appears to be running just fine; I can get it to report an FPS of 60 and am able to place breakpoints that do halt the code every frame. My OpenGLView class sets up as below, and this is where most of the new Swift 3 changes have taken place:
class BQSOpenGLView: NSOpenGLView {
var m_renderer: OpenGLRenderer = OpenGLRenderer()
var have_setup_renderer: Bool = false
var displayLink: CVDisplayLink?
var has_setup = false
var is_fullscreen: Bool = false
var grid_size: QSGridSize = QSMakeGridSize(1, 1)
var backing_scalar_changed: Bool = false
var backing_scalar: GLfloat = 0.0
override func awakeFromNib() {
backing_scalar = GLfloat((self.window?.backingScaleFactor)!)
NotificationCenter.default.addObserver(self, selector: #selector(BQSOpenGLView.willEnterFullscreen(_:)), name: NSNotification.Name.NSWindowWillEnterFullScreen, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BQSOpenGLView.willExitFullscreen(_:)), name: NSNotification.Name.NSWindowWillExitFullScreen, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(BQSOpenGLView.backingScaleChange(_:)), name: NSNotification.Name.NSWindowDidChangeBackingProperties, object: nil)
let attributes : [NSOpenGLPixelFormatAttribute] = [
NSOpenGLPixelFormatAttribute(NSOpenGLPFADoubleBuffer),
NSOpenGLPixelFormatAttribute(NSOpenGLPFADepthSize),
NSOpenGLPixelFormatAttribute(24),
NSOpenGLPixelFormatAttribute(NSOpenGLPFASampleBuffers),
NSOpenGLPixelFormatAttribute(1),
NSOpenGLPixelFormatAttribute(NSOpenGLPFASamples),
NSOpenGLPixelFormatAttribute(2),
NSOpenGLPixelFormatAttribute(NSOpenGLPFAOpenGLProfile),
NSOpenGLPixelFormatAttribute(NSOpenGLProfileVersion3_2Core),
NSOpenGLPixelFormatAttribute(0)
]
self.pixelFormat = NSOpenGLPixelFormat(attributes: attributes)
self.wantsBestResolutionOpenGLSurface = true
let context:NSOpenGLContext = NSOpenGLContext.init(format: self.pixelFormat!, share: nil)!
CGLEnable(context.cglContextObj!, kCGLCECrashOnRemovedFunctions)
self.openGLContext = context
}
override func prepareOpenGL() {
super.prepareOpenGL()
// The callback function is called everytime CVDisplayLink says its time to get a new frame.
func displayLinkOutputCallback(_ displayLink: CVDisplayLink, _ inNow: UnsafePointer<CVTimeStamp>, _ inOutputTime: UnsafePointer<CVTimeStamp>, _ flagsIn: CVOptionFlags, _ flagsOut: UnsafeMutablePointer<CVOptionFlags>, _ displayLinkContext: UnsafeMutableRawPointer?) -> CVReturn {
unsafeBitCast(displayLinkContext, to: BQSOpenGLView.self).renderFrame()
return kCVReturnSuccess
}
self.wantsLayer = true
self.wantsBestResolutionOpenGLSurface = true
CVDisplayLinkCreateWithActiveCGDisplays(&displayLink)
let success = CVDisplayLinkSetOutputCallback(displayLink!, displayLinkOutputCallback, Unmanaged.passUnretained(self).toOpaque())
if success != kCVReturnSuccess {
Swift.print ("No opengl")
}
CVDisplayLinkStart(displayLink!)
has_setup = true
NotificationCenter.default.post(name: Notification.Name(rawValue: kOPENGL_SETUP_NOTE), object: nil)
self.backingScaleChange(nil)
}
//..
}
The render method is:
func renderFrame() {
self.openGLContext?.makeCurrentContext()
CGLLockContext((self.openGLContext?.cglContextObj)!)
if !have_setup_renderer { //init only when locked all the context
self.backingScaleChange(nil)
m_renderer = OpenGLRenderer.init(defaultFBO: 0, screenSize: (self.window?.screen?.frame.size)!, backingScalar: self.backing_scalar)
have_setup_renderer = true
}
m_renderer.render()
CGLFlushDrawable((self.openGLContext?.cglContextObj)!)
CGLUnlockContext((self.openGLContext?.cglContextObj)!)
}
Is there a new Swift 3 way of setting up OpenGL or is the above code correct and the problem somewhere else?
Turns out to have been a subtly corrupt Xcode project. The only thing that didn't work was the OpenGL view. Perhaps just the nib was bad.
I started a new project and cut + paste'd the code into new files and laboriously rebuilt the UI and all worked just fine. That'll teach me not to set up the windows programmatically!
Related
I’m using the following code that gets triggered via a button to display the share sheet in my app:
func shareSheet() {
guard let urlShare = URL(string: "https://google.com") else { return }
let activityVC = UIActivityViewController(activityItems: [urlShare], applicationActivities: nil)
UIApplication.shared.windows.first?.rootViewController?.present(activityVC, animated: true, completion: nil)
}
This code brings up the warning:
'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead
I don't understand how I can get rid of it. Already checked the approach suggested here How to get rid of message " 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead" with AdMob banner? but it's not working. Any ideas how I can bypass the warning?
Many Thanks!
You can use following as UIApplication.shared.currentUIWindow()?.rootViewController
public extension UIApplication {
func currentUIWindow() -> UIWindow? {
let connectedScenes = UIApplication.shared.connectedScenes
.filter({
$0.activationState == .foregroundActive})
.compactMap({$0 as? UIWindowScene})
let window = connectedScenes.first?
.windows
.first { $0.isKeyWindow }
return window
}
}
I know to how to create local notification in Swift 3( I am new in this part), However, I want to create something like below image. All tutorials in the web are too old and I do not what should I do.
As you can see before extending notification , there are 2 buttons. after extending also there are 2 buttons with red and blue color.
Updated
Thanks Joern
The slide gesture only show clear. Is there any settings for showing both clear and view
The red and blue buttons are only available in iOS versions prior to iOS 10. With iOS 10 the notifications design changed. The slide gesture is used for the standard actions Clear and View. The custom actions Snooze and Confirm will be displayed when you force touch the notification or pull it down (for devices without force touch). If you are using a device with force touch the View button might not be shown.
The buttons look different now:
So, here is how you implement Local Notifications with Swift 3 / 4:
For iOS versions prior to iOS 10:
If you are supporting iOS versions prior to iOS10 you have to use the old (deprecated with iOS 10) UILocalNotification:
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
registerLocalNotification()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
scheduleLocalNotification()
}
func scheduleLocalNotification() {
let localNotification = UILocalNotification()
localNotification.alertTitle = "Buy milk"
localNotification.alertBody = "Remember to buy milk from store"
localNotification.fireDate = Date(timeIntervalSinceNow: 3)
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.category = "reminderCategory" // Category to use the specified actions
UIApplication.shared.scheduleLocalNotification(localNotification) // Scheduling the notification.
}
func registerLocalNotification() {
let reminderActionConfirm = UIMutableUserNotificationAction()
reminderActionConfirm.identifier = "Confirm"
reminderActionConfirm.title = "Confirm"
reminderActionConfirm.activationMode = .background
reminderActionConfirm.isDestructive = false
reminderActionConfirm.isAuthenticationRequired = false
let reminderActionSnooze = UIMutableUserNotificationAction()
reminderActionSnooze.identifier = "Snooze"
reminderActionSnooze.title = "Snooze"
reminderActionSnooze.activationMode = .background
reminderActionSnooze.isDestructive = true
reminderActionSnooze.isAuthenticationRequired = false
// Create a category with the above actions
let shoppingListReminderCategory = UIMutableUserNotificationCategory()
shoppingListReminderCategory.identifier = "reminderCategory"
shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .default)
shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .minimal)
// Register for notification: This will prompt for the user's consent to receive notifications from this app.
let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: [shoppingListReminderCategory])
UIApplication.shared.registerUserNotificationSettings(notificationSettings)
}
}
This will register the local notification and fires it 3 seconds after the user closes the app (for testing purposes)
For iOS 10 and later:
If you target your app to iOS 10 you can use the new UserNotifications framework:
import UIKit
import UserNotifications
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
registerUserNotifications()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
scheduleLocalNotification()
}
func registerUserNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
guard granted else { return }
self.setNotificationCategories()
}
}
func setNotificationCategories() {
// Create the custom actions
let snoozeAction = UNNotificationAction(identifier: "SNOOZE_ACTION",
title: "Snooze",
options: .destructive)
let confirmAction = UNNotificationAction(identifier: "CONFIRM_ACTION",
title: "Confirm",
options: [])
let expiredCategory = UNNotificationCategory(identifier: "TIMER_EXPIRED",
actions: [snoozeAction, confirmAction],
intentIdentifiers: [],
options: UNNotificationCategoryOptions(rawValue: 0))
// Register the category.
let center = UNUserNotificationCenter.current()
center.setNotificationCategories([expiredCategory])
}
func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Buy milk!"
content.body = "Remember to buy milk from store!"
content.categoryIdentifier = "TIMER_EXPIRED"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
// Create the request object.
let request = UNNotificationRequest(identifier: "Milk reminder", content: content, trigger: trigger)
// Schedule the request.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
}
You can check out a demo app that uses the UserNotifications framework here
The video I'm playing does not take the entire area of the UIView (named videoView), which has a gray color: iPhone 7 Plus Simulator Screenshot
Most of the answers claim that I need to either set the frame to bounds (of UIView) or set videoGravity to AVLayerVideoGravityResizeAspectFill. I've tried both, but for some reason it still does not fill the space entirely.
var avPlayer: AVPlayer!
var avPlayerLayer: AVPlayerLayer!
var paused: Bool = false
#IBOutlet weak var videoView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let theURL = Bundle.main.url(forResource:"HOTDOG", withExtension: "mp4")
avPlayer = AVPlayer(url: theURL!)
avPlayerLayer = AVPlayerLayer(player: avPlayer)
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayerLayer.frame = videoView.layer.bounds
videoView.layer.insertSublayer(avPlayerLayer, at: 0)
}
Any help will be appreciated. :)
After long time I found the answer.
Code below should be moved into viewDidAppear() like:
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
// Resizing the frame
avPlayerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
avPlayerLayer.frame = videoView.layer.bounds
videoView.layer.insertSublayer(avPlayerLayer, at: 0)
avPlayer.play()
paused = false
}
The layout was designed for iPhone SE (small screen), so when it was tested on a bigger screen the app was taking originally set size from the Auto-layout and shaping it according to that. By moving the code into viewDidAppear() the app resizes the window according to new constraints.
Just move the frame line avPlayerLayer.frame = videoView.layer.bounds into viewDidLayoutSubviews like this:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
avPlayerLayer.frame = videoView.layer.bounds
}
The rest should stick into the viewDidLoad function, just like you did.
Is there a more efficient way to animate text shivering with typewriting all in one sklabelnode? I'm trying to achieve the effect in some games like undertale where the words appear type writer style while they are shivering at the same time.
So far I've only been able to achieve it but with such luck:
class TextEffectScene: SKScene {
var typeWriterLabel : SKLabelNode?
var shiveringText_L : SKLabelNode?
var shiveringText_O : SKLabelNode?
var shiveringText_S : SKLabelNode?
var shiveringText_E : SKLabelNode?
var shiveringText_R : SKLabelNode?
var button : SKSpriteNode?
override func sceneDidLoad() {
button = self.childNode(withName: "//button") as? SKSpriteNode
self.scaleMode = .aspectFill //Very important for ensuring that the screen sizes do not change after transitioning to other scenes
typeWriterLabel = self.childNode(withName: "//typeWriterLabel") as? SKLabelNode
shiveringText_L = self.childNode(withName: "//L") as? SKLabelNode
shiveringText_O = self.childNode(withName: "//O") as? SKLabelNode
shiveringText_S = self.childNode(withName: "//S") as? SKLabelNode
shiveringText_E = self.childNode(withName: "//E") as? SKLabelNode
shiveringText_R = self.childNode(withName: "//R") as? SKLabelNode
}
// Type writer style animation
override func didMove(to view: SKView) {
fireTyping()
shiveringText_L?.run(SKAction.repeatForever(SKAction.init(named: "shivering")!))
shiveringText_O?.run(SKAction.repeatForever(SKAction.init(named: "shivering2")!))
shiveringText_S?.run(SKAction.repeatForever(SKAction.init(named: "shivering3")!))
shiveringText_E?.run(SKAction.repeatForever(SKAction.init(named: "shivering4")!))
shiveringText_R?.run(SKAction.repeatForever(SKAction.init(named: "shivering5")!))
}
let myText = Array("You just lost the game :)".characters)
var myCounter = 0
var timer:Timer?
func fireTyping(){
typeWriterLabel?.text = ""
timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(TextEffectScene.typeLetter), userInfo: nil, repeats: true)
}
func typeLetter(){
if myCounter < myText.count {
typeWriterLabel?.text = (typeWriterLabel?.text!)! + String(myText[myCounter])
//let randomInterval = Double((arc4random_uniform(8)+1))/20 Random typing speed
timer?.invalidate()
timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(TextEffectScene.typeLetter), userInfo: nil, repeats: false)
} else {
timer?.invalidate() // stop the timer
}
myCounter += 1
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch = touches.first
if let location = touch?.location(in: self) {
if (button?.contains(location))! {
print("doggoSceneLoaded")
let transition = SKTransition.fade(withDuration: 0.5)
let newScene = SKScene(fileNamed: "GameScene") as! GameScene
self.view?.presentScene(newScene, transition: transition)
}
}
}
}
As you can see, I had to animate each individual label node in a word "loser".
To create this effect:
For those who may be interested to Swift 4 I've realized a gitHub project around this special request called SKAdvancedLabelNode.
You can find here all sources.
Usage:
// horizontal alignment : left
var advLabel = SKAdvancedLabelNode(fontNamed:"Optima-ExtraBlack")
advLabel.name = "advLabel"
advLabel.text = labelTxt
advLabel.fontSize = 20.0
advLabel.fontColor = .green
advLabel.horizontalAlignmentMode = .left
addChild(self.advLabel)
advLabel.position = CGPoint(x:frame.width / 2.5, y:frame.height*0.70)
advLabel.sequentiallyBouncingZoom(delay: 0.3,infinite: true)
Output:
something i have a lot of experience with... There is no way to do this properly outside of what you are already doing. My solution (for a text game) was to use NSAttributedString alongside CoreAnimation which allows you to have crazy good animations over UILabels... Then adding the UILabels in over top of SpriteKit.
I was working on a better SKLabel subclass, but ultimately gave up on it after I realized that there was no way to get the kerning right without a lot more work.
It is possible to use an SKSpriteNode and have a view as a texture, then you would just update the texture every frame, but this requires even more timing / resources.
The best way to do this is in the SK Editor how you have been doing it. If you need a lot of animated text, then you need to use UIKit and NSAttributedString alongside CoreAnimation for fancy things.
This is a huge, massive oversight IMO and is a considerable drawback to SpriteKit. SKLabelNode SUCKS.
As I said in a comment, you can subclass from an SKNode and use it to generate your labels for each characters. You then store the labels in an array for future reference.
I've thrown something together quickly and it works pretty well. I had to play a little bit with positionning so it looks decent, because spaces were a bit too small. Also horizontal alignement of each label has to be .left or else, it will be all crooked.
Anyway, it'S super easy to use! Go give it a try!
Here is a link to the gist I just created.
https://gist.github.com/sonoblaise/e3e1c04b57940a37bb9e6d9929ccce27
I am developing music app but for lock screen control i am not able to assign time duration and elapsed time
here is my code
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.previousTrackCommand.isEnabled = true;
commandCenter.previousTrackCommand.addTarget(self, action:#selector(home_ViewController.btn_rewind(_:)))
commandCenter.nextTrackCommand.isEnabled = true
commandCenter.nextTrackCommand.addTarget(self, action:#selector(home_ViewController.btn_fast(_:)))
commandCenter.playCommand.isEnabled = true
commandCenter.playCommand.addTarget(self, action:#selector(home_ViewController.play_player))
commandCenter.pauseCommand.isEnabled = true
commandCenter.pauseCommand.addTarget(self, action:#selector(home_ViewController.pause_player))
commandCenter.togglePlayPauseCommand.isEnabled = true
commandCenter.togglePlayPauseCommand.addTarget(self, action:#selector(home_ViewController.togglePlay_Pause))
commandCenter.skipBackwardCommand.isEnabled = false
commandCenter.skipForwardCommand.isEnabled = false
if #available(iOS 9.1, *) {
commandCenter.changePlaybackPositionCommand.isEnabled = true
} else {
// Fallback on earlier versions
return
}
and media info
func setLockInfo()
{
let url = URL(string: song_UrlString)
let data = try? Data(contentsOf: url!)
let art = MPMediaItemArtwork.init(image: UIImage(data: data!)!)
let songInfo :[String : Any] = [MPMediaItemPropertyTitle :st_title,MPMediaItemPropertyArtwork : art]
MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo
}
I am getting title and image but lock screen is not displaying time
I am using SWIFT 3 to code
It's not displaying the time because you're not telling it to display the time.
To show the playback time, your nowPlayingInfo dictionary needs to include values for the keys:
MPNowPlayingInfoPropertyElapsedPlaybackTime, so it knows what the current time is when you start playing,
MPMediaItemPropertyPlaybackDuration, so it knows what the current time is relative to in the bar, and
MPNowPlayingInfoPropertyPlaybackRate, so it can automatically update the playback time UI without you needing to periodically set the current time.
If you want the playback time bar to be interactive (that is, allow jumping to a different time instead of just displaying the current time, register a changePlaybackPositionCommand with your remote command center.
Swift 3 example with all commands woking, including changePlaybackPositionCommand:
func remotePlayerInit() {
UIApplication.shared.beginReceivingRemoteControlEvents()
let commandCenter = MPRemoteCommandCenter.shared()
commandCenter.pauseCommand.addTarget(self, action: #selector(self.pauseSongTouch(_:)))
commandCenter.playCommand.addTarget(self, action: #selector(self.playSongTouch(_:)))
commandCenter.nextTrackCommand.addTarget(self, action: #selector(self.nextSongTouch(_:)))
commandCenter.previousTrackCommand.addTarget(self, action: #selector(self.previousSongTouch(_:)))
commandCenter.changePlaybackPositionCommand.addTarget(self, action: #selector(self.changedThumbSlider(_:)))
setLockInfo()
}
func changedThumbSlider(_ event: MPChangePlaybackPositionCommandEvent) -> MPRemoteCommandHandlerStatus {
audioPlayer.currentTime = event.positionTime
setLockInfo()
return .success
}
func setLockInfo()
{
let image = PlayerVC.songs[PlayerVC.currentSelection].image
let artwork = MPMediaItemArtwork.init(boundsSize: image.size, requestHandler: { (size) -> UIImage in
return image
})
let songInfo: [String: Any] = [MPMediaItemPropertyTitle: PlayerVC.songs[PlayerVC.currentSelection].name,
MPMediaItemPropertyArtwork: artwork,
MPNowPlayingInfoPropertyElapsedPlaybackTime: TimeInterval(audioPlayer.currentTime),
MPNowPlayingInfoPropertyPlaybackRate: 1,
MPMediaItemPropertyPlaybackDuration: audioPlayer.duration,
MPMediaItemPropertyArtist: "Artist"]
MPNowPlayingInfoCenter.default().nowPlayingInfo = songInfo
}