Menu
  • HOME
  • TAGS

Reference method from different class as curried function

swift,methods,currying

As methods in Swift are curried class functions, compiler has to decide which overload to choose. To reference instance's merge method you need to specify it's exact type: let instanceMerge: RACSignal -> RACSignal! -> RACSignal! = RACSignal.merge...

How to disable the Copy/Hide feature in UIImagePickerController when long pressing a image …?

ios,swift,ios8,uiimagepickercontroller,ios8.3

Its orientation issues. UIImagePickerController wont support landscape mode.. Try this code source :: https://gist.github.com/mkeremkeskin/0ed9fc4a2c0e4942e451 - (BOOL)shouldAutorotate { UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation]; if ( orientation == UIDeviceOrientationPortrait | orientation == UIDeviceOrientationPortraitUpsideDown) { return YES; } return NO; } - (NSUInteger)supportedInterfaceOrientations { return (UIInterfaceOrientationMaskPortrait | UIInterfaceOrientationMaskPortraitUpsideDown); } -...

Unexpectedly found nil while unwrapping an Optional value - Plist

ios,swift,plist

Seems to be no error in your code, Check that the arrays in plist has the same naming as in your code might be mistaken something with keys. You can check that by right-click on plist and Open-as then choose source code Like : objectForKey("name") called <key>name</key> objectForKey("image") called <key>image</key>...

Chance of a conditional occurring in Swift: Xcode

xcode,swift,if-statement,conditional,percentage

You can use arc4random_uniform to create a read only computed property to generate a random number and return a boolean value based on its result. If the number generated it is equal to 1 it will return true, if it is equal to 0 it will return false. Combined with...

Extra table cells when UITableViewController is embedded into a Container in a UIViewController

ios,swift,uitableview,uiviewcontroller

You just need to add this to your code in viewDidLoad. self.tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero]; EDIT: sorry i was written in objective -c here is in swift. self.tableView.tableFooterView = UIView(frame:CGRectZero) The tableview will display what appear to be extra blank rows to fill out the bounds if there are not...

Swift Singleton not Working

swift,singleton

If you use this method of singletons, to actually access the singleton you need to use DataWarehouse.sharedData, instead of DataWarehouse(), when you are 'constructing' the datawarehouse object within the other classes. At the moment you never actually access sharedInstance. If you are using Swift 1.2 and prefer, you can use...

iOS 8 Swift CS193P Calculator Bug Switch Operation

ios,swift

Your code looks fine, it looks like you accidentally placed a breakpoint in your code, see that blue-looking arrow to the left of the green-highlighted line? Do one of the following: Go ahead and right click that and click Delete Breakpoint Drag and drop that breakpoint into your view controller...

Parse: How can I update all rows with the same key value?Thanks

ios,swift,parse.com

Parse has a functions to object see to save many objects (see documentation here) PFObject.saveAllInBackground(array, block: { (succeeded: Bool, error: NSError!) -> Void in if (error != nil) { println("Error saving: \(error)") } }) Unfortunately the documentation is not update to Swift but you can see a list of the...

What's the equivalent of finally in Swift

swift,try-catch-finally

If you are thinking about the SWIFT 2.0 error handling to be the same thing as exception you are missunderstanding. This is not exception, this is an error that conforms to a protocol called ErrorType. The purpose of the block is to intercept the error thrown by a throwing function...

Swift Range on the fly 1…12.contains(1) Cannot invoke 'contains' with (Int)

swift,range

In this case the problem was that of operator precedence: (1...12).contains(1) // -> true (the code does look ambiguous otherwise)...

How can I display the time offset (years, months, weeks, …) from two dates at my labels?

ios,xcode,swift

I have created a new extension to output the offset components as string for you: import UIKit extension NSDate { func yearsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: date, toDate: self, options: nil).year } func monthsFrom(date:NSDate) -> Int{ return NSCalendar.currentCalendar().components(.CalendarUnitMonth, fromDate: date, toDate: self, options: nil).month } func weeksFrom(date:NSDate) -> Int{...

Extension function asking for return type instead of parameter

swift,uifont,swift-extensions

museoSansRounded900 should be a class method as you're trying to call it directly on the UIFont class (which makes it basically a constructor). class func museoSansRounded900(size: CGFloat) -> UIFont ... ...

MFMessageComposeViewControllerDelegate not being called

ios,swift

It's crashing because your handler object is getting released and deallocated right after the call to handler.sendMessage(), and then a delegate callback is attempted on that now-deallocated object when you try to send or hit cancel. The object is getting released and deallocated because nothing is holding a strong reference...

Parse: Facebook user unlink and login again creates two user table entries

ios,swift,parse.com

You need to link the user to a facebook account, the code below does this link for you: if !PFFacebookUtils.isLinkedWithUser(user) { PFFacebookUtils.linkUserInBackground(user, withReadPermissions: nil, { (succeeded: Bool?, error: NSError?) -> Void in if succeeded { println("Woohoo, the user is linked with Facebook!") } }) } From Parse.com documentation: The steps...

Extra CALayer's subLayers in iOS

ios,swift,calayer

Every UIView is backed up by a CALayer, the view hierarchy and the layer hierarchy are connected to each other. If you print out the subviews, you will see that the view has two subviews of type _UILayoutGuide which represent the controller's topLayoutGuide and bottomLayoutGuide. Every subview has a layer...

AutoLayout complains about constraints for 2 UITextFields with no borders

ios,xcode,swift,autolayout,nslayoutconstraint

"Add Missing Constraints" is not always a good idea to add constraints..rather you should always prefer to add constraints manually... Here is the image for your UI...I used wAnyhAny layout as it is good practice for add constraints for universal devices... I used simply width constraint for textfield, rather you...

animating a view on top of uitableview

ios,swift,autolayout

In initializeSettingsView() add nibView.setTranslatesAutoresizingMaskIntoConstraints(false). And then in viewDidload add the hight constraint to settingsView constraints.append(NSLayoutConstraint(item: settingsView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 90.0)) And you do not need to set the position of settingsView, since it will be layout at the right position based on...

How can I fix crash when tap to select row after scrolling the tableview?

ios,xcode,swift,uitableview,tableviewcell

Because you are using reusable cells when you try to select a cell that is not in the screen anymore the app will crash as the cell is no long exist in memory, try this: if let lastCell = self.diceFaceTable.cellForRowAtIndexPath(lastIndexPath) as! TableViewCell{ lastCell.checkImg.image = UIImage(named: "uncheck") } //update the data...

UITapGestureRecognizer sender is the gesture, not the ui object

ios,xcode,swift,uigesturerecognizer

You can get a reference to the view the gesture is added to via its view property. In this case you are adding it to the button so the view property would return you you the button. let button = sender.view as? UIButton ...

Best way to save traffic in iOS Parse App

ios,arrays,swift,parse.com,traffic

You can create Parse class for your feed objects. After that create an array column to store objectIds of users who added your feed item to favorit. When you want to find all the objects specific user bookmarked do something like PFQuery *query = [PFQuery queryWithClassName:@"feedObjects"]; [query whereKey:@"favoritesArray" equalTo:@"YOUR USER...

SwiftyJSON Reading JSON Array issue

json,swift,swifty-json

json["Cars"] is an array, so for example to get the first item via SwiftyJSON: println(json["Cars"][0]["Brand"].stringValue) In a JSON string, { and } are delimiters for dictionaries, whereas [ and ] are delimiters for arrays. EDIT: Following your comment, yes, you can loop over the array: if let cars = json["Cars"].array...

Detect UIImageView Touch in Swift

ios,swift,uiimageview

You can put an UITapGestureRecognizer inside your UIImageView using Interface Builder or in code (as you want), I prefer the first. The you can put an @IBAction and handle the tap inside your UIImageView, Don't forget to set the UserInteractionEnabled to true in Interface Builder or in code. @IBAction func...

Get NSString from NSMutableArray on Swift

swift,nsmutablearray

Try componentsJoinedByString func cualidadesToString() -> NSString{ return cualidades.componentsJoinedByString(",") } But you should use Swift's builtin String and Array types to make it more type-safe. var cualidades = [String]() func addCualidad(cualidad: String){ cualidades.append(cualidad) } func delCualidad(cualidad: String){ if let cindex = find(cualidades, cualidad) { cualidades.removeAtIndex(cindex) } } func cualidadesToString() -> String{...

compile error on FirebaseHandle

ios,swift,firebase

The method observeEventType returns a Uint ( UInt8 actually ). So your firebaseHandle variable should be defined like that : var firebaseHandle: UInt8 = 0 Hope it helps....

How to save text field value in uicollectionviewcell

swift,uitextfield,uicollectionviewcell

Implement in your ViewController the UITextFieldDelegate protocol, specifically the textField:didEndEditing method. Save your indexPath.row in the textField.tag as you're doing, and set the delegate to the controller, where you can save the value. This is a very simplistic example: class MyViewController : UITableViewController { var texts = [Int:String]() func tableView(tableView:...

How to use NSRegularExpression in Swift 2.0?

ios,swift,swift2

NSRegularExpression(pattern:) throws an error if the pattern is invalid. In your case, the pattern is fixed, so an invalid pattern would be a programming error. This is a use-case for the "forced-try" expression with try!: extension String { func isEmail() -> Bool { let regex = try! NSRegularExpression(pattern: "^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}$", options:...

Swift: String contains Character?

string,swift,character

You can use the free-standing find function, like this: let s = "hello" if (find(s, "x") != nil) { println("Found X") } if (find(s, "l") != nil) { println("Found "L) } ...

UIView within a container view not showing

ios,xcode,swift

All you have to do is Set the label ":" in centre vertical and horizontally and align all the constraints according to it . align the blue view giving it top , height , width and centre X to the label ":" and all other views giving them top and...

UIColor initializer (cannot find an initializer of type 'UIColor' that accepts …) error [duplicate]

swift,uipickerview,uicolor

Use CGFloat not Float Check the API docs when you get an error like this...

Calling dispatch_sync from a concurrent queue - does it block entirely?

ios,objective-c,multithreading,swift,grand-central-dispatch

dispatch_sync will block the caller thread until execution completes, a concurrent queue has multiple threads so it will only block one of those on that queue, the other threads will still execute. Here is what Apple says about this: Submits a block to a dispatch queue for synchronous execution. Unlike...

XCode 7 error: “A launch storyboard or xib must be provided unless the app requires full screen”

ios,swift,uistoryboard,xcode7

Starting from iOS9 and Xcode 7 you are required to provide a LaunchScreen.storyboard for your launch screen in order to support the new multitasking feature on iPad. To opt out of being eligible to participate in Slide Over and Split View, add the UIRequiresFullScreen key to your Xcode project’s Info.plist...

How to code a generic Swift class which stores a Generator of the same type

swift,generics

You have to use the generator type as the type placeholder G, and refer to its element type as G.Element: class MyGenericClass<G : GeneratorType> { var source : G var itemsProcessed : [ G.Element ] = [] init(source: G) { self.source = source } func getValue() -> G.Element? { let...

AppleScript (or swift) add hours to time

swift,date,applescript

You need to pick the hours as an individual variable, like shown below: set currentDate to current date set newHour to ((hours of currentDate) + 8) You can also use this for days, minutes and seconds. This will work. You can then use the variables to construct a new date...

How to call my custom alert controller function to display in other view controller?

ios,swift,uialertcontroller

Change your method like so: func displayLoadingAlert(viewController: UIViewController?) -> UIAlertController { var controllerToPresent = viewController if controllerToPresent == nil { controllerToPresent = self } // Most of your code controllerToPresent.presentViewController(loadingAlertController, animated: true, completion: nil) return loadingAlertController } Then when you're calling the alert: loadingAlertController.displayLoadingAlert(self) Alternatively: Rename the method displayLoadingAlert to...

Is this Swift syntax efficient?

ios,swift,syntax

It fires everytime the getter is called. No way this could be optimized away. You might want to keep a preset colors array in sync with the photos property, i.e. change it directly when setting the photos. I also dislike the tight coupling in that place which seems unnecessary. I...

Factorials in Swift

swift,factorial

As others have said you can use libraries that support larger numbers, or just don't allow values that are too big. Note that if you want to handle very large values you might need to use a loop rather than a recursive algorithm because recursion can cause a Stack Overflow....

Resize a UITableView

swift,uitableview,resize,frame

My first guess was that you were using AutoLayout. Changes to view frames often don't have any effect in that case. Have you double-checked to make sure it's turned off for you storyboard? Failing that, the most likely cause of changing having no effect is broken outlets. Add a println...

iOS Swift: Sound not playing on iPhone Simulator

ios,iphone,swift,audio,ios-simulator

You just need to move the declaration of your audioPlayer out of your method. Try like this: var audioPlayer:AVAudioPlayer! func playSound() { if let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") { audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.prepareToPlay() audioPlayer.play() } } ...

Swift timer in milliseconds

xcode,swift

As Martin says in his comment, timers have a resolution of 50-100 ms (0.02 to 0.1 seconds). Trying to run a timer with an interval shorter than that will not give reliable results. Also, timers are not realtime. They depend on the run loop they are attached to, and if...

Display an UIAlertView when app launches

swift,swift2

You should be displaying the alert in your viewDidAppear: function. To present a subview or another view controller, the parent view controller has to be in the view hierarchy. The viewDidAppear function "notifies the view controller that its view was added to a view hierarchy." * From the documentation So,...

coordinate deprecated as of iOS 7

ios,iphone,swift

Replace the following in your code var latestLocation: AnyObject = locations[locations.count - 1] with the following. var latestLocation = locations.last as! CLLocation ...

Swift SpriteKit edgeLoopFromRect Issue

ios,swift,sprite-kit,cgrect,skphysicsbody

You are probably on the right track about .sks file. When scene is loaded from the .sks file the default size is 1024x768. Now you can dynamically set that based on the view size. So, swap your viewDidLoad with viewWillLayoutSubviews like this: override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() if let scene...

Why using ? in this case is not working? (swift)

ios,swift

If you don't know whether your image exists or not, you should use optional binding, try this: func setBGImage(myImageName: String) { if let bgColor = UIImage(named: myImageName) { self.view.backgroundColor = UIColor(patternImage: bgColor) } } If myImage exists, it will assign it to bgColor, in which is assigned to self.view.backgroundColor. or,...

looping variable in swift

swift,for-loop,uiimage

You don't need to create a new variable for each image, try this: for var i = 1; i < 8; i++ { images.append(UIImage(named: "image\(i)")) } This loop will create an array with 8 images without create the variables image1 to image8. I hope that help you!...

Cannot invoke method with argument list of type KeyType in Swift

swift,generics

I think that best solution for your case would be changing class declaration to: class EventDispatcher<U: EventDispatcherProtocol> { typealias KeyType = U.T And it will also simplify creation of the EventDispatcher with skipping the redundant type declarations: var dispatcher = EventDispatcher<CustomListener<CustomEvent>>() EDIT: Since the code was altered multiple times while...

Admob interstitial ad delegate

ios,swift,admob,interstitial

GADInterstitial delegate is a weak stored property, so you should create a stored property in your class: var adDelegate : AdDelegate? // to store the delegate func createInterstitial()->GADInterstitial { var interstitial = GADInterstitial() interstitial.adUnitID = "ca-app-pub-6938332798224330/6206234808"; adDelegate = AdDelegate() interstitial.delegate = adDelegate //delegate is weak so we need to store...

How can I show ONLY the date (and not the time) using NSDateFormatter?

ios,iphone,swift

var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = NSLocale(localeIdentifier: @"en_US") let d = NSDate() let s = dateFormatter.stringFromDate(d) ...

Swift compiler macro / flag for String value alternative

swift

Macros are evil. They have been abused for things like this and it's not a clean solution. You have the following options (some of them already mentioned by you). Info.plist The most simple, easy to read and edit. Not good for big configurations. Your own .plist. Easy to read and...

iAd is NOT loading with Swift

swift,iad

Apparently my ad wasn't loading. All of a sudden it loads fine now.

I am trying to use Core Data and load a table view with its contents in order and in sections

ios,swift,core-data,tableview

Take a look here for the approach to read section-wise data - http://www.andrewcbancroft.com/2015/03/05/displaying-data-with-nsfetchedresultscontroller-and-swift/ and here iOS UITableView sections with fetchedResultsController confusion...

what's the purpose of double question mark in swift [duplicate]

ios,swift

It is called nil coalescing operator. If highs is not nil than it is unwrapped and the value returned. If it is nil then [ChartHighlight]() returned. It is a way to give a default value when an optional is nil.

How to get time difference based on GMT on Swift

ios,swift

I think your problem is that you are using a calendar with an unset time zone. Your calculation of adding 60*60*24*2 to the current time does not account for the two days when some timezones change to and from daylight savings time. Those days are 23 and 25 hours long....

startAccelerometerUpdatesToQueue Type of expression is ambiguous without more context

swift,core-motion,swift2

This is one of those problems that can be solved by retyping the code from scratch. It appears that the second parameter to startAccelerometerUpdatesToQueue() is now an object of type (CMAccelerometerData?, NSError?) -> Void instead of (CMAccelerometerData!, NSError!) -> Void. You just need to rewrite your call to reflect this....

Can't figure out coder aDecoder: NSCoder

ios,xcode,swift

Your custom initializer cannot initialize the immutable property. If you want it to be immutable then, instead of creating a custom initializer, just initialize in one of the required or designated initializer. Like this, class AddBook: UIViewController { @IBOutlet weak var bookAuthor: UITextField! @IBOutlet weak var bookTitle: UITextField! let bookStore:...

Why label still append 0 once press clear button “C”?

xcode,swift

Just add this condition into displayHistory() method : if history.text == "0" { history.text = historyLabel }else { history.text = historyLabel + history.text! } ...

UIViewController LifeCycle

swift,uiviewcontroller,segue

In order to use an unwind segue, you start by setting up a method in the destination view controller. @IBAction func unwind(segue: UIStoryboardSegue) { // unwind } Note, that this method is placed in the destination view controller. The view controller being unwound to. From here, we need not the...

Characters and Strings in Swift

ios,string,swift,unicode,character

When a type isn't specified, Swift will create a String instance out of a string literal when creating a variable or constant, no matter the length. Since Strings are so prevalent in Swift and Cocoa/Foundation methods, you should just use that unless you have a specific need for a Character—otherwise...

How to do a “show (e.g Push)” segue programatically without animation?

ios,objective-c,swift,storyboard,segue

What the show (e.g. Push) segue does internally is to call -[UIViewController showViewController:sender:] Calling this method on your view controller itself, will trigger the appropriate way of presenting the view controller you are passing. // Swift self.showViewController(viewControllerToShow, sender: self) // Objective-C [self showViewController: viewControllerToShow sender: self]; The animation can be...

Google Drive API (GTL) - Create multiple folder paths in order?

ios,objective-c,swift,google-drive-sdk,google-api-objc-client

Avoid using a synchronous for loop. The createFolder function should call back when it's complete; that callback should start the next loop iteration.

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring

appendString: is from NSMutableString, stringByAppendingString: is from NSString. The first one mutates the existing NSMutableString. Adds to the end of the receiver the characters of a given string. The second one returns a new NSString which is a concatenation of the receiver and the parameter. Returns a new string made...

PFUser not unwrapped - swift

ios,xcode,swift

Here is explanation: What is an "unwrapped value" in Swift? PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the user canceled fb login") //add uialert return } //new user else if user!.isNew { println("user singed up through FB") //get information from fb then save to...

When trying to get dynamically created UILabel to wrap, text disappears

xcode,swift,word-wrap,cgrect,sizetofit

Changing the position of sizeToFit() after assigning text did the job as suggested by Bartlomiej above

How can I convert an Int array into a String? array in Swift

ios,arrays,swift,casting,type-conversion

Airspeed Velocity gave you the answer: var arr: [Int] = [1,2,3,4,5] var stringArray = arr.map { String$($0) } Or if you want your stringArray to be of type [String?] var stringArray = arr.map { Optional(String$($0)) } This form of the map statement is a method on the Array type. It...

Parse JSON output from AlamoFire

json,swift,nsurlrequest

If I believe the println of aStatus, the property title is a String, not a Dictionary. Change this part in your code (cast as String instead of as NSDictionary): if let user = aStatus["title"] as? String { println( "TITLE \(user)") } ...

Parse and Swift Geopoints not saving

swift,parse.com,geopoints

That is because you are setting it but you are not saving the value you just set: if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") PFUser.currentUser().saveInBackground() } } ...

Orientation of screen?

ios,iphone,swift,sprite-kit

You have to allow all orientations in the project settings, then only orientations allowed are Portrait or Upside down portrait in your viewController except the GameViewController: // BaseViewController override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.currentDevice().userInterfaceIdiom == .Phone { return UIInterfaceOrientationMask.Portrait.rawValue | UIInterfaceOrientationMask.PortraitUpsideDown.rawValue } else { return .All } }...

create a popup window with just a textview/string and a button SWIFT ios 8

iphone,swift,ios8,popup,xcode6

It sounds like you want a UIAlertController, check this out: @IBAction func popUpButton(sender: UIButton) { //This is where you declare and initialize your `UIAlertController` let alertController = UIAlertController(title: "Alert", message: "Test Alert", preferredStyle: .Alert) //You give the `UIAlertController` an action, which basically has a cancel button, that just cancels out...

How to hide scroll bar of UICollectionView

ios,swift,uicollectionview

[collectionView setShowsHorizontalScrollIndicator:NO]; [collectionView setShowsVerticalScrollIndicator:NO]; ...

Expected declaration error when adding subview

ios,swift,xcode6

You can declare instance variable/properties (and assign default values) in your class outside of any function but you cannot include any other code. All of the lines of code after the let square = UIView() need to go in a function, probably an initialiser. ...

Do I have to use both of these methods?

ios,swift,uitableview

No, you don't have to use both. Either you go with reloadCell technique or cell updates via beginUpdate and endUpdate. When you are reloading a particular row, internally table view system creates 2 cell and then blends in the new one with. You can remove the beginUpdates and endUpdates and...

Beacon / IOS CLLocationManager get current region

ios,swift,cllocationmanager,ibeacon

You can use the locationManager:didDetermineState:forRegion: callback, which tells you if you are either Inside, Outside or Unknown. You can force yourself to get a callback by calling locationManager.requestStateForRegion(region) when your app starts up. See more here: https://developer.apple.com/library/ios/documentation/CoreLocation/Reference/CLLocationManagerDelegate_Protocol/#//apple_ref/occ/intfm/CLLocationManagerDelegate/locationManager:didDetermineState:forRegion:...

How to create UITableViewCells with complex content in order to keep scrolling fluent

ios,swift,uitableview,cocoa-touch,ios-charts

What you're trying to do is going to inevitably bump into some serious performance issues in one case or another. Storing all cells (and their data into memory) will quickly use up your application's available memory. On the other hand dequeueing and reloading will produce lags on some devices as...

Is There A Neat Way to Attach a Completion Block to an NSURLSessionDataDelegate Callback in Swift?

ios,swift,nsurlsession,completion-block

What I've done in the past is to create some sort of transaction object. I set up a download manager (as a singleton) to create an array of transaction objects. I make the transaction object the delegate of the URL session (Actually this predates NSURLSession - I did it with...

IOS rightBarButtonItem on UINavigationController in swift

ios,swift,uibarbuttonitem,uinavigationitem

You should set the menu_button_ as the rightBarButtonItem of your viewController rather than the navigationController. Try self.navigationItem.rightBarButtonItem = menu_button_ instead self.navigationController!.navigationItem.rightBarButtonItem = menu_button_ ...

Stop async operations on window close

swift,cocoa,appdelegate

I use this approach [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0]; ...

Obj-C Instance method returning a instanceType called from Swift - Function produces expected type 'UIImage!' error

ios,objective-c,swift

If you look at the method you have defined in Objective C image category, it is instance method and you are trying to call it using UIImage class in swift. You can basically use either one of the following two approaches, Either, self.backgroundImageView.image = self.someImage.applyDarkEffect() // notice the method does...

UITableCell not resizing properly

ios,swift,uitableview

Try to use layoutIfNeeded for update constraint immediately. For fix warning, you should set one of your vertical constraint priority to 999. All works properly if set Accessory view to None...

How can I make both of these UICollectionViews appear in the same View?

ios,swift,uicollectionview

You cant use same functions inside a single class. Instead you will need to identify each collection view somehow (by creating outlets or giving them a tag) and then in each function check the collectionview parameter and compare it with your collection views. Example : func collectionView(collectionView: UICollectionView, numberOfItemsInSection section:...

Swift - UILabel from URL

ios,swift,uilabel,nsurl

If you don't want to use sessions, you can also use the simpler NSURLConnection Class, something like this: let url = NSURL(string: "https://wordpress.org/plugins/about/readme.txt") let request = NSURLRequest(URL: url!) NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) dispatch_async(dispatch_get_main_queue()) { // Do stuff on the UI thread self.textField.text =...

What is the best practice add video background view?

ios,objective-c,swift,video

First of all, you have two main choices: use a imageView with a GIF or use a video for background with AVPlayer or MPMoviePlayerController. You can find a lot of example for both ways, here's a few: use a GIF for cool background video cover iOS In reply to your...

Why is there a lag in my game everytime my sound is being played in swift?

ios,swift,avaudioplayer

lower the quality/bitrate of the audio that you play.

Blocking a Loop Using UIAlertController

ios,objective-c,swift,uialertcontroller

Use Recursive Function rather than loop Example var name:[String] = ["abcd","efgh","ijkl","mnop","qrst","uvwx"] self.friendReuqest(name, index: 0) func friendReuqest(name:[String],index:Int) { if index < name.count { let alertController = UIAlertController(title: name[index], message: "Would you like to accept this friend request?", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction: UIAlertAction = UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Cancel){ (action: UIAlertAction!) -> Void...

Unichar variable in Swift

swift,unichar

In Swift, the character literals are of type Character. let exclamationMark: Character = "!" See Strings and Characters For advanced readers: You can also extend unichar with the capability to accept character literals: extension unichar : UnicodeScalarLiteralConvertible { public typealias UnicodeScalarLiteralType = UnicodeScalar public init(unicodeScalarLiteral scalar: UnicodeScalar) { self.init(scalar.value) }...

SKEmitterNode particles lag at start

ios,xcode,swift,particles,skemitternode

The solution was setting the advanceSimulationTime to exactly 1.0 sec. I'm not entirely sure why this is the case, but I suppose that the creation "animation" takes up this time. Anyway, case closed and thanks for the help to everyone, especially lchamp since he suggested the solution....

iOS 9 not opening Instagram app with URL SCHEME

ios,swift,swift2,ios9

iOS 9 has made a small change to the handling of URL scheme. You must whitelist the url's that your app will call out to using the LSApplicationQueriesSchemes key in your Info.plist. Please see post here: http://awkwardhare.com/post/121196006730/quick-take-on-ios-9-url-scheme-changes The main conclusion is that: If you call the “canOpenURL” method on a...

Passing String array to a function

ios,swift,nsarray

First of all, your function is not a class level function and you are calling the method directly using class name. Try like this. var array:[String] = [] // fill the array array.append(uniqueId as! String) // pass the array to a function: GamePrefrences.setLevelsArray(array) Function declaration. class func setLevelsArray(arr:[String]) { GamePrefrences.levels_array...

How do I use my class in AppDelegate.swift

ios,swift,appdelegate

Make sure that Member is declared in a place that your AppDelegate can "see" it. This concept is called "scope" and is crucial to many programming languages, including Swift. Classes declared inside other classes, for example, are not visible outside that class (unless they're given specific access modifiers). If that...

iOS: What is the callback when tapped on the empty space between keyboard and search bar to dismiss the keyboard when search bar is active

ios,objective-c,swift

How about -searchBarTextDidEndEditing: in UISearchBarDelegate?

Omitting the return type in Swift closures

swift

I would not expect that example to have worked but it does In many cases, Swift can often infer types of variables and expressions. In this case, Swift looks at the value you're returning and can infer the type. If I modify that closure to specify a return type...

How to prevent duplicate entry on parse?

ios,objective-c,iphone,swift,parse.com

I suggest to implement a simple beforeSave trigger, on Parse Cloud code, in order to check if the new entry song already exist (basically you're going to make one or more field uniques. For example: Parse.Cloud.beforeSave("Musics", function(request, response) { var newEntrySong = request.object; var querySongs = new Parse.Query("Musics"); querySongs.equalTo("title", newEntrySong.get("title"));...

Regular expression to get url in string swift

ios,regex,swift

You turn off case sensitivity using an i inline flag in regex: (?i)https?:\\/.* See Foundation Framework Reference for more information on available regex features. (?ismwx-ismwx) Flag settings. Change the flag settings. Changes apply to the portion of the pattern following the setting. For example, (?i) changes to a case insensitive...

Implementing Applovin Ads with Swift & SpriteKit

ios,swift,applovin

You likely need to enable "Test Mode" for your app in the AppLovin dashboard in order to force test ads to serve for your area. Please send any questions to [email protected] for further assistance.

How to get NSTableView to use a custom cell view mixed with preset cell views?

osx,swift,cocoa,nstableview,nstableviewcell

I'd try just giving the default cell your own identifier in Interface Builder... ...then just use that in conjunction with makeViewWithIdentifier:: func tableView(tableView: NSTableView, viewForTableColumn tableColumn: NSTableColumn?, row: Int) -> NSView? { var viewIdentifier = "StandardTableCellView" if let column = tableColumn { switch column.identifier { case "nameColumn": viewIdentifier = "nameCellView"...