Use of unresolved identifier 'dispatch_get_main_queue' using SWIFT - macos

I am having difficulty using 'dispatch_get_main_queue()' in SWIFT with the base SDK set to 10.9. The code that I am using is a simple dispatch_async call shown below:
dispatch_async(dispatch_get_main_queue()){
// Code here
}
However it is generating the error: Use of unresolved identifier 'dispatch_get_main_queue'. It works as expected when the base SDK is set to 10.10, but not at 10.9. I use it in objective-c in non-swift applications which use the base SDK 10.9 but I cannot figure out why it is not working with Swift.
I have tried to look into it but have currently been unable to find anything about why this is happening and what I can do to resolve it/achieve similar functionality. I would be very grateful if anyone can shed any light on this or point me in the right direction.
So my question is: Is there a way I can resolve this (or at least achieve similar functionality)?
EDIT 1 -
This is the full function I have created:
func addSubview(aView: NSView, fillView: Bool, removeExisting: Bool)
{
dispatch_async(dispatch_get_main_queue()){
if (aView != nil)
{
if (removeExisting)
{
for (var subview: NSView) in self.subviews() as NSView[]
{
subview.removeFromSuperview();
}
}
if (fillView)
{
aView.setAutoresizingMask(NSViewWidthSizable | NSViewHeightSizable);
aView.setFrame(NSMakeRect(0, 0, self.frame().size.width, self.frame().size.height));
}
self.addSubview(aView);
}
}
}
EDIT 2 - Replaced 'if (aView != null)' to 'if (aView != nil)' as suggested. I am not sure how I managed to make that rookie error!

Use it in a function. This should work:
func test() {
dispatch_async(dispatch_get_main_queue()) {
}
}
Works fine on my laptop with deployment target 10.9
Or in your app delegate maybe something like this:
func applicationDidFinishLaunching(aNotification: NSNotification?) {
// Insert code here to initialize your application
dispatch_async(dispatch_get_main_queue()) {
}
}
First you should replace if (aView != null) to if (aView != nil)
Swift uses nil not null

If view can be nil you should use optional type:
func addSubview(view: NSView?, fillView: Bool, removeExisting: Bool) {
dispatch_async(dispatch_get_main_queue()){
if let aView = view {
if removeExisting {
...

Related

logInWithReadPermissions(_:handler:)' is deprecated: use logInWithReadPermissions:fromViewController:handler: instead

Using the latest XCode, I'm getting this error:
'logInWithReadPermissions(_:handler:)' is deprecated:
use logInWithReadPermissions:fromViewController:handler: instead'
How would I alternatively re-format my code? here is the whole function that it is in:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"]) {
(facebookResult: FBSDKLoginManagerLoginResult!,facebookError: NSError!) in
print("Facebook login failed. Error \(facebookError)")
}
}
Xcode 8.2 beta (8C30a) :
fbLoginManager.logIn(withReadPermissions:["email"], from: self, handler: {
(result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult? = result
if(fbloginresult?.isCancelled)! {
//Show Cancel alert
} else if(fbloginresult?.grantedPermissions.contains("email"))! {
//self.returnUserData()
//fbLoginManager.logOut()
}
}
})
Figured it out guys! If anyone is lurking on this post, here is the new code:
#IBAction func fbBtnPressed(sender: UIButton!) {
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { (facebookResult: FBSDKLoginManagerLoginResult!, facebookError: NSError!) -> Void in
print("Facebook login failed. Error \(facebookError)")
}
}
If your fbBtnPressed function is in a view controlle class, just pass self to the fromViewController parameter.
facebookLogin.logInWithReadPermissions(["email"], fromViewController: self) { ... }
A note though, it's encouraged in Swift and Obj-C that your function names prioritize readability over being compact. For example, I would name your button handler facebookLoginButtonPressed. It's longer but much more readable.

Swift Type Inference Not Working (Xcode 7.1.1)

This is my first question on StackOverflow so please go easy on me.
I've been struggling with getting Swift to invoke the appropriate generic overload.
Suppose I have the following protocol -
protocol MyProtocol { }
And I have the following generic methods -
func foo<T>() -> T
func foo<T: MyProtocol>() -> T
One would expect that invoking foo() with a return type of T conforming to MyProtocol would invoke the appropriate overload.
let bar: MyProtocol = foo()
The above code actually invokes the following function during runtime and Cmd + Click in the IDE navigates to the wrong overload as well.
func foo<T>() -> T
For some reason I cannot get this to work properly in Xcode 7.1.1.
Am I missing something completely fundamental here or is this another Swift quirk?
EDIT
Adding an example of this behavior in action as per matt's request.
protocol MyProtocol { }
class MyProtoClass : MyProtocol { }
class Bar {
func foo<T>(value: T) {
print("T is Generic")
}
func foo(value: MyProtocol) {
print("T conforms to MyProtocol")
}
}
class MyClass<T> {
var value: T
init(value: T) { self.value = value }
var b = Bar()
func print() {
b.foo(value)
}
}
MyClass<MyProtocol>(value: MyProtoClass()).print()
MyClass<String>(value: "").print()
Copying and pasting the above code into a Swift command line application and executing yields the following output.
T is Generic
T is Generic
I think the problem here is that protocols in generics (and generally in Swift) don't work the way you want them to. They are not acting as first-class types. I know that's rather vague... but look at it this way; if you eliminate the func foo<T>(value: T) version of foo, your code won't even compile. In other words, Swift isn't making a choice of foo and choosing wrong; it's saying that b.foo(a1.value) does not call func foo<T: MyProtocol>(value: T).
I have a vague feeling that this is related to my question here:
Protocol doesn't conform to itself?
Okay, I am going to answer my own question here.
After some investigation it seems that Swift wants you to implement an extension with a type constraint on the generic parameter.
extension MyClass where T : MyProtocol {
func print() {
b.foo(value)
}
}
I know this doesn't really solve the problem but it was sufficient enough for me as a work around in my real world use case.
The above sample would wind up looking something like the following.
protocol MyProtocol { }
class MyProtoClass : MyProtocol { }
class Bar {
func foo<T>(value: T) {
print("T is Generic")
}
func foo(value: MyProtocol) {
print("T conforms to MyProtocol")
}
}
class MyClass<T> {
var value: T
init(value: T) { self.value = value }
var b = Bar()
func print() {
b.foo(value)
}
}
extension MyClass where T : MyProtocol {
func print() {
b.foo(value)
}
}
MyClass<MyProtoClass>(value: MyProtoClass()).print()
MyClass<String>(value: "").print()

Why do I get this error "fatal error: unexpectedly found nil while unwrapping an Optional value" in Swift Xcode?

I'm trying to ad an Ad network called StartApps and 'Im following this guideline.(https://github.com/StartApp-SDK/Documentation/wiki/iOS-Swift-InApp-Documentation#step3)
The problem is that I get this error:
fatal error: unexpectedly found nil while unwrapping an Optional value
At
viewController.startAppAd!.showAd()
in my GameScene.swift. Why does this happen. Thanks!
class GameViewController: UIViewController {
var startAppAd: STAStartAppAd?
override func viewDidLoad() {
super.viewDidLoad()
startAppAd = STAStartAppAd()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
startAppAd!.loadAd()
}
//Im calling the function showsAds() in the GameScene.swift file
class GameScene: SKScene {
var viewController = GameViewController()
override func didMoveToView() {
}
// interstitial ads randomnly appear after hero hits enemy
func interstitialAdsRandom(){
var randomAd = Int(arc4random() % 2)
println(randomAd)
if randomAd == 0 {
viewController.startAppAd!.showAd()
println("showad")
}
}
}
}
You get the error because you are force-unwrapping the variable startAppAd. That is what force-unwrapping does.
If you change that exclamation point to a question mark, it will make it so that the method call is skipped if the optional contains nil.
startAppAd?.loadAd()
If you want to write the best code, you should use "if let" syntax, known as optional binding:
if let startAppAd = startAppAd
{
startAppAd.loadAd()
}
else
{
//startAppAd is nil. Handle that error case
}

Parse/Swift getObjectInBackgroundWithId query not working

I am trying to run the query to get object in background with ID but when I run the method query.getObjectInBackgroundWithId , I am getting the error message:
"Cannot invoke 'getObjectInBackgroundWithId' with an argument list of type (string, block: (PFObject!,NSError?) -> Void"
The same thing happens when I use user.signUpInBackgroundWithBlock so I'm thinking maybe Xcode updated some of the features while using 'block's and now maybe the syntax is different? Any ideas?
Here's a snippet of my code:
http://imgur.com/1CvfhbU
YES!!! Thank you!
The new sample code for getObject is:
query.getObjectInBackgroundWithId("Oaq79bhv53") {
(gameScore: PFObject?, error: NSError?) -> Void in
if error == nil && gameScore != nil {
println(gameScore)
} else {
println("error")
}
}
I figured it out!
user.signUpInBackgroundWithBlock{(succeeded: Bool, signUpError: NSError?) -> Void in
Swift 4.2:
query.getObjectInBackground(withId: "YourId") { (gameScore, error) in
if error == nil {
// Success!
print(gameScore)
} else {
// Fail!
}
}

How to use NSWindowOcclusionState.Visible in Swift

I am trying to implement window toggling (something I've done many times in Objective-C), but now in Swift. It seams that I am getting the use of NSWindowOcclusionState.Visible incorrectly, but I really cannot see my problem. Only the line w.makeKeyAndOrderFront(self) is called after the initial window creation.
Any suggestions?
var fileArchiveListWindow: NSWindow? = nil
#IBAction func tougleFileArchiveList(sender: NSMenuItem) {
if let w = fileArchiveListWindow {
if w.occlusionState == NSWindowOcclusionState.Visible {
w.orderOut(self)
}
else {
w.makeKeyAndOrderFront(self)
}
}
else {
let sb = NSStoryboard(name: "FileArchiveOverview",bundle: nil)
let controller: FileArchiveOverviewWindowController = sb?.instantiateControllerWithIdentifier("FileArchiveOverviewController") as FileArchiveOverviewWindowController
fileArchiveListWindow = controller.window
fileArchiveListWindow?.makeKeyAndOrderFront(self)
}
}
Old question, but I just run into the same problem. Checking the occlusionState is done a bit differently in Swift using the AND binary operator:
if (window.occlusionState & NSWindowOcclusionState.Visible != nil) {
// visible
}
else {
// not visible
}
In recent SDKs, the NSWindowOcclusionState bitmask is imported into Swift as an OptionSet. You can use window.occlusionState.contains(.visible) to check if a window is visible or not (fully occluded).
Example:
observerToken = NotificationCenter.default.addObserver(forName: NSWindow.didChangeOcclusionStateNotification, object: window, queue: nil) { note in
let window = note.object as! NSWindow
if window.occlusionState.contains(.visible) {
// window at least partially visible, resume power-hungry calculations
} else {
// window completely occluded, throttle down timers, CPU, etc.
}
}

Resources