Rectangle 27 75

You can set background color of view to the UIColor with alpha, and not affect view.alpha view?.backgroundColor = UIColor(white: 1, alpha: 0.5)

This looks like what I'm looking for. I will try it on Monday when I'm home and let you know!

endGameView.backgroundColor = UIColor(white: 1, alpha: 0.5)

ios - Swift UIView background color opacity - Stack Overflow

ios swift uiview alpha
Rectangle 27 31

Setting alpha property of a view affects its subviews. If you want just transparent background set view's backgroundColor proprty to a color that has alpha component smaller than 1.

view.backgroundColor = UIColor.whiteColor().colorWithAlphaComponent(0.5)
UIColor.white.withAlphaComponent(0.5)

ios - Swift UIView background color opacity - Stack Overflow

ios swift uiview alpha
Rectangle 27 1

You can change the size of your sprite to fit the size the scene

bgImage.size = self.size

Of course if the proportions of the scene are different from the proportions of the sprite, the sprite will be stretched.

thank you very much the picture has over stretched but at least its fitting the screen

Use the scene size, not the view size. @harreskhan, this may be happening because you have .AspectFill as your scale filter

Nope, using the scene size can stretch the sprite as well if the scene size has different proportions than the sprite size. Furthermore if the scene is much larger than the view you'll get the sprite to be oversized.

yes, but your scene size may not be your view size, a background image for a scene should not be be filling based on the view, it should be filling based on the scene, that is why I said use the scene size, not the view size

a background image for a scene should not be be filling based on the view, it should be filling based on the scene

sprite kit - Swift Spritekit Background image - Stack Overflow

swift sprite-kit
Rectangle 27 1

First of all, your image sizes are everywhere, and I don't think you understand how Xs work.

Basically, they are the ratios of which the resolution increases based on the device tipe (non-retina, retina, retina HD).

You need an image for a button. You support iPhone, from the iPhone 3gs to the 6 Plus. That means you have all 3 types of displays supported.

  • the iPhone 3Gs is non retina, it has a ration of 1 (1 pixel in a point), so your image should be 50x50 pixels => image@1x.png = 50x50 pixels
  • the 4, 4s, 5 and 5s are retina, they have a ration of 2 (2 pixels in a point), so your image should be 100x100 pixels => image@2x.png = 100x100 pixels
  • the 6 and 6+ are RetinaHD, they have a ratio of 3 (3 pixels in a point), so your image should be 150x150 pixels => image@3x.png = 150x150 pixels

Secondly, in your case, the image is 750 x 1334. So image@2x should be 1500 x 2668 and image@3x 2250 x 4002.

ios - Unable to set a perfect image for swift spritekit background - S...

ios swift sprite-kit
Rectangle 27 63

In the target settings Capabilities tab Background Modes, if you check "Remote Notifications", application:didReceiveRemoteNotification: will get triggered as soon as notification arrives (as long as the app is in the background), and in that case there is no way to tell whether the user will tap on the notification.

If you uncheck that box, application:didReceiveRemoteNotification: will be triggered only when you tap on the notification.

It's a little strange that checking this box will change how one of the app delegate methods behaves. It would be nicer if that box is checked, Apple uses two different delegate methods for notification receive and notification tap. I think most of the developers always want to know if a notification is tapped on or not.

Hopefully this will be helpful for anyone else who run into this issue. Apple also didn't document it clearly here so it took me a while to figure out.

I have Background Modes set to "OFF" completely, but still get notified when a notification arrives with the app in background mode.

Great! This helped me. It's a pity however that I need to switch off remote notifications. I would like to prefetch data when a push notification arrives AND detect the user tap. I can't find a way to achieve this.

I set the Background mode to "ON" mode and enable the remote notifications. Still not able to detect the notification event.

I have same problem Background mode is set to "ON" and enabled remote notification, but still not get notified when notification arrives to the app in background mode

@Bao - I think it will cause rejection on Appstore, as this option is basically used to download content related to notification in background. So if you are not downloading any content Apple may reject your app. developer.apple.com/library/ios/documentation/iPhone/Conceptual/

swift - iOS push notification: how to detect if the user tapped on not...

ios swift push-notification apple-push-notifications
Rectangle 27 38

I've been looking for the same thing as you and actually found a solution that does not require remote notification to be ticked off.

To check whether user has tapped, or app is in background or is active, you just have to check the application state in

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler{

    if(application.applicationState == UIApplicationStateActive) {

        //app is currently active, can update badges count here

    }else if(application.applicationState == UIApplicationStateBackground){

        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here

    }else if(application.applicationState == UIApplicationStateInactive){

        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here

    }

What about app being UIApplicationStateInactive as a result of user engaging with Notification centre (swipe from top) or Control centre (swipe from bottom) while the app is on screen. Apparently, there is no way to tell whether APNS was received in Inactive state or user actually tapped it.

@KostiaKim You're right, but that's a super edge case...other than that, this answer is the most valid in terms of separating between app in foreground...user tapping...app in background

Thanks, this kind of demystifies everything. Remember that in order for the delegate method to be called when the app is in the background, the push notification has to include the content-available key, but then the notification must be silent (i.e. not include a sound or badge) as stated in the official docs.

@KostiaKim I was actually able to fix the issue of not knowing whether the control center was open or if the user actually tapped the notification by adding a boolean that is set to true in the func applicationDidEnterBackground(_ application: UIApplication) and false in the func applicationDidBecomeActive(_ application: UIApplication) this allowed me to show the in app notifications when the app is inactive due to the control center or the notifications list

it boggles my mind why Apple didn't present a different event or simply add a flag in the metadata to indicate that the user actually interacted with the notification. Having to 'deduce' whether the user took an action based on ambient information about the application state is pretty unreasonable for a key bit of information that affects the user's expectation of application behaviour. Perhaps the only thing to do is to create a custom action to open the app with that information?

swift - iOS push notification: how to detect if the user tapped on not...

ios swift push-notification apple-push-notifications
Rectangle 27 445

A lot has been modernized in Swift 3.0. Running something on the background thread looks like this:

DispatchQueue.global(qos: .background).async {
    print("This is run on the background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

And if someone wants a more Swift like syntax, I've created Async that adds some sugar to the syntax like Async.background {}

I am using your code in xCode 6.0.1 and ios 8.It gives error as "QOS_CLASS_BACKGROUND" return class and it is of type UInt32 and "dispatch_get_global_queue" requires 1st parameter as int so type error is coming.

So in Xcode 6.1.1 I am not getting an error for using just plain simple "QOS_CLASS_BACKGROUND". Is it fixed?

@LucasGoossen Yes, it has been fixed. I've update the post accordingly.

@NikitaPronchik Isn't this clear from the answer? Else feel free to make a edit to it.

ios - How to use background thread in swift? - Stack Overflow

ios swift
Rectangle 27 445

A lot has been modernized in Swift 3.0. Running something on the background thread looks like this:

DispatchQueue.global(qos: .background).async {
    print("This is run on the background queue")

    DispatchQueue.main.async {
        print("This is run on the main queue, after the previous code in outer block")
    }
}
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
dispatch_async(backgroundQueue, {
    print("This is run on the background queue")

    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        print("This is run on the main queue, after the previous code in outer block")
    })
})

As of Swift 1.1 Apple didn't support the above syntax without some modifications. Passing QOS_CLASS_BACKGROUND didn't actually work, instead use Int(QOS_CLASS_BACKGROUND.value).

And if someone wants a more Swift like syntax, I've created Async that adds some sugar to the syntax like Async.background {}

I am using your code in xCode 6.0.1 and ios 8.It gives error as "QOS_CLASS_BACKGROUND" return class and it is of type UInt32 and "dispatch_get_global_queue" requires 1st parameter as int so type error is coming.

So in Xcode 6.1.1 I am not getting an error for using just plain simple "QOS_CLASS_BACKGROUND". Is it fixed?

@LucasGoossen Yes, it has been fixed. I've update the post accordingly.

@NikitaPronchik Isn't this clear from the answer? Else feel free to make a edit to it.

ios - How to use background thread in swift? - Stack Overflow

ios swift
Rectangle 27 15

This is a fine way to change the color of a UITabBar. If you want to avoid setting the color in every viewController that is embedded inside of your UITabBarController, you could also create a subclass of UITabBarController and set it there. This way no matter what page comes up first, the color will be set.

To create a subclass of UITabBarController, just go to file > new > file > cocoa touch class...Then setup your file like in this photo

Now in your storyboard, set the custom class on your tabBarController

Finally, in your file you created MyTabBarController (or whatever you called it):

class MyTabBarController: UITabBarController {

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    self.tabBar.barTintColor = .blueColor()
}
...

Thanks Jeff, I can see how the subclass method would work. You're saying that I should bind my normal storyboard TabBarController object to a custom MyTabBarController code, where I set the colors. So when the TBC gets loaded, the colors are enforced. (I have no code bound to that controller right now.) That seems like an elegant way to do it, thank you. Could I do the same thing to change colors in a NavBar -- bind the storyboard nav bar to a subclass of UINavigationBar, etc?

PS. But didn't I read somewhere that someone said the Apple guidelines doc said, "TabBarControllers are not meant to be subclassed"? Would doing so block me from app store acceptance? PPS. Your idea worked like a charm. Thanks

I am not aware of any official Apple guidelines against subclassing UITabBarController. I have several apps in the app store that have used this in their implementation. If you read someone saying not to do this, they are most likely just saying that you shouldn't make major modifications in the subclass (like changing the size of the tabBar, or something of that nature)

Using your exact syntax, the idea works. But in a separate problem, now I see that when I click the More... tab, the colors disappear. I read somewhere here on SO that the More... tab uses a second tab controller/tab bar/table view, so any colors I put on the main tab bar will not carry across to the More... tab bar. Maybe it's easier to just leave it gray, like Apple wants it.

Admittedly, I have never implemented a tabBar with a More tab on it, so I am not sure how that works. Have you tried just setting the color of the tabBar under barTint in the storyboard?

ios - Swift 2.2 How to change background color of tab bar controller -...

ios swift2 uitabbarcontroller uitabbar
Rectangle 27 2

override func didMove(to view: SKView) {
    background.position = CGPoint(x: 0, y: 0)
    background.size.width = self.size.width
    background.size.height = self.size.height
    background.anchorPoint = CGPoint(x: 0.5,y: 0.5)

    self.addChild(background)
}

AnchorPoint (0.5,0.5) which centers the image in its position.

wait, If this works, this means your scene's anchor point is 0.5, 0.5. That means you do not have to set anything to background except size (all the variables here is default variable except self.size.width and self.size.height, that will scale the sprite to the scene size)

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

ios - Swift - Add a background image to a Spritekit scene - Stack Over...

ios swift sprite-kit
Rectangle 27 4

You can also set it from InterfaceBuilder by changing color's opacity:

ios - Swift UIView background color opacity - Stack Overflow

ios swift uiview alpha
Rectangle 27 19

if ([UIApplication sharedApplication].applicationState == UIApplicationStateInactive)
{
    // user has tapped notification
}
else
{
    // user opened app from app icon
}

Although it does not make totally sense to me, it seems to work.

It wouldn't work in this scenario. I tried that before. When that checkbox was checked (see my accepted answer for details), when the notification arrives, your line with comment "// user has tapped notification" will be entered, even though the user didn't tap the notification (the notification just arrived).

I disagree. I have "Remote notifications" checked in my background capabilities and it works the way described in my answer. I have "Background fetch" checked as well. Maybe that causes the change?

maybe that was the case. Thanks for pointing out.

Yupe, this is the solution. tnx.

swift - iOS push notification: how to detect if the user tapped on not...

ios swift push-notification apple-push-notifications
Rectangle 27 103

The best practice is to define a reusable function that can be accessed multiple times.

e.g. somewhere like AppDelegate.swift as a Global Function.

func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
        if(background != nil){ background!(); }

        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(popTime, dispatch_get_main_queue()) {
            if(completion != nil){ completion!(); }
        }
    }
}

A. To run a process in the background with a delay of 3 seconds:

backgroundThread(3.0, background: {
            // Your background function here
    })

B. To run a process in the background then run a completion in the foreground:

backgroundThread(background: {
            // Your function here to run in the background
    },
    completion: {
            // A function to run in the foreground when the background thread is complete
    })

C. To delay by 3 seconds - note use of completion parameter without background parameter:

backgroundThread(3.0, completion: {
            // Your delayed function here to be run in the foreground
    })

nice snippet, should be the correct answer. @Dale Clifford

Very nice. Would you please confirm, the delay only works for the completion block. So that means that the delay in A. has no impact, and the background block executes immediately without delay.

Getting error, backgroundThread is not declared

if(background != nil){ background!(); }
background?()
DispatchQueue.global(priority: Int(DispatchQoS.QoSClass.userInitiated.rawValue)).async {
cannot invoke initializer for type 'Int' with an argument list of type '(qos_class_t)'
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async

ios - How to use background thread in swift? - Stack Overflow

ios swift
Rectangle 27 103

The best practice is to define a reusable function that can be accessed multiple times.

e.g. somewhere like AppDelegate.swift as a Global Function.

func backgroundThread(delay: Double = 0.0, background: (() -> Void)? = nil, completion: (() -> Void)? = nil) {
    dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) {
        if(background != nil){ background!(); }

        let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
        dispatch_after(popTime, dispatch_get_main_queue()) {
            if(completion != nil){ completion!(); }
        }
    }
}

A. To run a process in the background with a delay of 3 seconds:

backgroundThread(3.0, background: {
            // Your background function here
    })

B. To run a process in the background then run a completion in the foreground:

backgroundThread(background: {
            // Your function here to run in the background
    },
    completion: {
            // A function to run in the foreground when the background thread is complete
    })

C. To delay by 3 seconds - note use of completion parameter without background parameter:

backgroundThread(3.0, completion: {
            // Your delayed function here to be run in the foreground
    })

nice snippet, should be the correct answer. @Dale Clifford

Very nice. Would you please confirm, the delay only works for the completion block. So that means that the delay in A. has no impact, and the background block executes immediately without delay.

Getting error, backgroundThread is not declared

if(background != nil){ background!(); }
background?()
DispatchQueue.global(priority: Int(DispatchQoS.QoSClass.userInitiated.rawValue)).async {
cannot invoke initializer for type 'Int' with an argument list of type '(qos_class_t)'
DispatchQueue.global(qos: DispatchQoS.QoSClass.userInitiated).async

ios - How to use background thread in swift? - Stack Overflow

ios swift
Rectangle 27 3

  • start the download in a thread, allowed to run for a few minutes in background (with UIApplication.shared.beginBackgroundTask)
  • download files one by one in a loop with a custom download method allowing to set a timeout
  • if yes, download the file with a timeout of min(60, UIApplication.shared.backgroundTimeRemaining - 5)
  • if no, stop downloading and save the download progress in the user defaults, in order to be able to resume it when the user navigates back to the app
  • when the user navigates back to the app, check if a state has been saved, and if so resume the download.

This way the download continues for a few minutes (3 on iOS 10) when the user leaves the app, and is pause just before these 3 minutes are elapsed. If the user leaves the app in background for more than 3 minutes, he must come back to finish the download.

iOS Swift download lots of small files in background - Stack Overflow

ios swift download background
Rectangle 27 3

in Swift 3.0

yourView.backgroundColor = UIColor.black.withAlphaComponent(0.5)

This works for me in xcode 8.2.

ios - Swift UIView background color opacity - Stack Overflow

ios swift uiview alpha
Rectangle 27 1

Check out this neat tutorial where they precisely teach you about Background Modes and how to play audio in the background.

ios - Swift Playing Audio Playlist in Background - Stack Overflow

ios swift swift3 avfoundation
Rectangle 27 8

If somebody wants it in swift 3.0

switch application.applicationState {
    case .active:
        //app is currently active, can update badges count here
        break
    case .inactive:
        //app is transitioning from background to foreground (user taps notification), do what you need when user taps here
        break
    case .background:
        //app is in background, if content-available key of your notification is set to 1, poll to your backend to retrieve data and update your interface here
        break
    default:
        break
    }

On which trigger we should add this code , didReceiveRemoteNotification or didFinishLaunchingWithOptions?

@Hamid sh,,,, I received push notification in all state i.e. when app is in forground, background, close(terminated)..! but my problem is that how to increment badge count when app is in background state and close (terminate) state???? Please tell me in details how i do it....? my app badge count is only increase when app is in forground state.....? if possible please tell me in brief.......!

swift - iOS push notification: how to detect if the user tapped on not...

ios swift push-notification apple-push-notifications
Rectangle 27 91

From Xcode 8.2.1 Swift 3.0.2 onwards

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: .mixWithOthers)
    print("Playback OK")
    try AVAudioSession.sharedInstance().setActive(true)
    print("Session is Active")
} catch {
    print(error)
}

@ardakaraca You are welcome

@LeoDabus where do we put that code? I added that to the viewDidLoad and app delegate and it didn't work. Confused as to where it should go?

Hey @LeoDabus it still turns off. I'm adding it in the cellForRowAtIndexPath as well as in the App Delegate and it's not working. I also added it in the custom cell without any luck. Any ideas what could be wrong? Btw, I'm using YouTubeSDK, but I'm assuming that sound is sound and it doesn't matter. Please let me know. Thank you!

ios - How to Play Audio in Background Swift? - Stack Overflow

ios swift audio avfoundation
Rectangle 27 33

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
    //All stuff here
})

Just for clarification, why would this be used instead of the accepted answer? Is this just an older API?

@Sirens I would think this would be very useful for apps supporting < iOS 8.

didn't work in Swift 3

ios - How to use background thread in swift? - Stack Overflow

ios swift