FAQ Database Discussion Community


Extra CALayer's subLayers in iOS

ios,swift,calayer
I have created a new single view project written in swift and print self.view.layer.sublayers.count. The number is 2, but I haven't add any layer or UIView. override func viewDidLoad() { super.viewDidLoad() println(self.view.layer.sublayers.count) // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() {...

Omitting the return type in Swift closures

swift
I'm working through one of the examples at the very handy and colourfully named site here, specifically : func applyMutliplication(value: Int, multFunction: Int -> Int) -> Int { return multFunction(value) } applyMutliplication(2, {value in value * 3 }) Notice that the closure given when calling applyMultiplication() does not specify a...

MFMessageComposeViewControllerDelegate not being called

ios,swift
I am trying to implement a class that will present a MFMessageComposeViewController from the AppDelegate. The class declaration looks like this: import UIKit import MessageUI class MyClass: NSObject, MFMessageComposeViewControllerDelegate { func sendAMessage() { // message view controller let messageVC = MFMessageComposeViewController() messageVC.body = "Oh hai!" messageVC.recipients = ["8675309"] // set...

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

ios,objective-c,multithreading,swift,grand-central-dispatch
Let's say I hypothetically call a dispatch_sync from a concurrent queue - does it block the entire queue or just that thread of execution?

Swift Singleton not Working

swift,singleton
Trying to get a Singleton class going in Swift. I'm not getting any errors, but its also just plain not working properly. Here's the code: // The Singleton class: class DataWarehouse { class var sharedData:DataWarehouse { struct Static { static var onceToken : dispatch_once_t = 0 static var instance :...

UITableCell not resizing properly

ios,swift,uitableview
While working on my first iPhone app, I ran into a problem while attempting to use ‘automatic’ table cell resizing. When I load the app, the first few cells will always be huge, about 6 times the size it should be. Then, when I scroll down and back up, they’ll...

UITapGestureRecognizer sender is the gesture, not the ui object

ios,xcode,swift,uigesturerecognizer
I've got a button called and I gave it a UIGestureRecognizer so that an IBAction is only run when the button is long pressed. You do this by adding a UILongPressGestureRecognizer to the button iteself. Then you control drag that gesture recognizer to a function like this: @IBAction func handleGesture(sender:...

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

xcode,swift,word-wrap,cgrect,sizetofit
I'm trying to display some description text that varies from a couple of words to a hundred words. I've set my UILabel to wrap to compensate using the code below descText.frame = CGRect(x: 115, y: 160, width: 465, height: 21) descText.textAlignment = NSTextAlignment.Left descText.numberOfLines = 0 descText.lineBreakMode = NSLineBreakMode.ByWordWrapping descText.sizeToFit()...

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

ios,swift,avaudioplayer
The sound plays everytime I tap the screen but there is a slight hiccup in the game where you could see it lag the screen. How would I fix this? class level1: SKScene, SKPhysicsContactDelegate, GKGameCenterControllerDelegate { var jumpSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("tapsound", ofType: "wav")!) var jumpAudioPlayer = AVAudioPlayer() override func didMoveToView(view:...

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

ios,objective-c,swift
I have this instance method in an existing Obj-C UIImage category: - (UIImage *)applyDarkEffect; I'm trying to call it from a Swift file like so: self.backgroundImageView.image = UIImage.applyDarkEffect(image) But get this compiler error: Function produces expected type 'UIImage!'; did you mean to call it with '()'? ...

IOS rightBarButtonItem on UINavigationController in swift

ios,swift,uibarbuttonitem,uinavigationitem
I'm trying to put a rightBarButtonItem on a second view controller of an UINavigationViewController stack. I'm creating and setting the button in viewDidLoad of the view controller that I want to show. My actual code looks like this: override func viewDidLoad() { super.viewDidLoad() menu_button_ = UIBarButtonItem(image: UIImage(named: "menu"), style: UIBarButtonItemStyle.Plain...

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

swift,uipickerview,uicolor
This question already has an answer here: Swift UIColor initializer - compiler error only when targeting iPhone5s 2 answers I know it is not an appropriate way to do this but for the purpose of learning I have a picker control with four components and 255 rows in each...

Display an UIAlertView when app launches

swift,swift2
I'm trying to add a UIAlertView or Controller when the app first loads. Currently, I have this code in my viewDidLoad method. let welcomeAlert = UIAlertController(title: "hola", message: "this is a test.", preferredStyle: UIAlertControllerStyle.Alert) welcomeAlert.addAction(UIAlertAction(title: "ok.", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(welcomeAlert, animated: true, completion: nil) Why won't the alert view...

Unichar variable in Swift

swift,unichar
How to define a unichar type variable in Swift likes '\0' '\n' in Objective-C ? In Swift, func previousCharacter() -> unichar { return "\n" //Error } Compiler gave me an error: Cannot convert return expression of type 'String' to expected return type 'unichar' But in Objective-C, it will more easy...

How to prevent duplicate entry on parse?

ios,objective-c,iphone,swift,parse.com
I' trying to save song info to parse, but if the song already exist in parse I want my code just do nothing. I've tried this code below: var Music = PFObject(className:"Musics") var query = PFQuery(className:"Musics") query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]?, error: NSError?) -> Void in if error == nil {...

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

ios,swift
My purpose is to assign the color of UIView from an existing image: self.myView.backgroundColor = UIColor(patternImage: UIImage(named: "04_white_back_page2")?) As I understand, I don’t know whether this UIImage(named: "04_white_back_page2") contains nil or a value, so: if it has value use it, and otherwise just consider the whole expression nil, and do...

SKEmitterNode particles lag at start

ios,xcode,swift,particles,skemitternode
I'm playing around with SKEmitterNode in my own little game. I'm shooting a cannon ball and when the ball hits one of the boxes in the scene, the box gets destroyed and a particle effect with a simple texture "BOOM" is created to make a transition when the box disappears....

Can't figure out coder aDecoder: NSCoder

ios,xcode,swift
I'm making an app for archiving books, I'm at the point of hooking up a button to save the data, but I can't get past the initialisation. Here is the error Xcode is giving me : Property 'self.bookStore' not initialised at super.init call. And here is my code : import...

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

osx,swift,cocoa,nstableview,nstableviewcell
I have a NSTableView configured in Interface Builder which uses several default cell views. However the first column's cell view needs to be created from a custom class. How do I implement NSTableViewDataSource method tableView.viewForTableColumn() so that it creates the default cell views for the remaining columns? Here's my method...

SwiftyJSON Reading JSON Array issue

json,swift,swifty-json
I'm trying to read a json array data as below with my code but I'm getting empty result all the time while I can print the whole data. Please where would be my issue? I've read this topic but I couldn't get the result. Topic Link {"Cars":[{"Brand":"Alfa Romeo"},{"Brand":"Audi"},{"Brand":"BMW"},{"Brand":"Citroen"},{"Brand":"Dacia"},{"Brand":"Fiat"},.......... My code...

How to hide scroll bar of UICollectionView

ios,swift,uicollectionview
i m working on an UICollectionView class, and it will display scroll bar when i scroll on the list, it's possible to hide scroll bar when scrolling?

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
I get it to load, I get the sections to load, but I cant get the cells in each section to load correctly. It restarts from the beginning in each section effectively duplicating each cell. My entity name is Customer and it holds the following attributes. firstName, lastName, phoneNumber,email, notes,...

How to use NSRegularExpression in Swift 2.0?

ios,swift,swift2
I have written this function in String Extension and can't figure out the error. func isEmail() -> Bool { let regex = NSRegularExpression(pattern: "^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$", options: [.CaseInsensitive]) return regex.firstMatchInString(self, options: nil, range: NSMakeRange(0, characters.count)) != nil } The error is: Call can throw, but it is not marked with 'try' and...

Cannot invoke method with argument list of type KeyType in Swift

swift,generics
I am working on custom message dispatcher in Swift. I want to have dispatcher which can: dispatch enums as events or whatever what is Hashable. Every object which implements one protocol might be added as listeners Here is the code: import Foundation protocol EventDispatcherProtocol: class { typealias T: Hashable func...

Crash on pushViewController

ios,swift,viewcontroller,pushviewcontroller
I'm trying to push a ViewController, but my app crashes every time. I'm using the UIImagePickerControllerDelegate to take a picture, and once the picture has been taken, this code runs: func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let pickedImage = info[UIImagePickerControllerEditedImage] as! UIImage // Reset the cameraButton and...

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

ios,swift,uicollectionview
I have two UICollectionViews that I need in one View. They have two different CollectionViewCell classes. The first CollectionView cell class is ConfirmOffersCollectionViewCell and the second is ConfirmRequestsCollectionViewCell. I am able to have both CollectionViews appear and function if I set both cells to the same class, but they display...

What is the best practice add video background view?

ios,objective-c,swift,video
I want to add background view with video (or gif) like in app "Uber" I'd like to use video background view for a long time in my app. And I want to know the answers to these questions: What of them will consume less battery energy Can I use it...

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

ios,objective-c,swift,google-drive-sdk,google-api-objc-client
I'm using the Google APIs Client Library for Objective-C (GTL) to access the Google Drive API. According to it's Introduction to the Google APIs Client Library for Objective-C, Query execution by the service is inherently asynchronous. Which means when you try to create a path like: root/a/b/c, before you can...

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

ios,xcode,swift
I am getting Use of unresolved identifier 'self' in my app. After reading this link, I wrapped the code in a class. Note: I am using an extension I got from this answer at S.O. class SetDate { var seconds = date2.secondsFrom(date1) var minutes = date2.minutesFrom(date1) var hours = date2.hoursFrom(date1)...

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

ios,swift,uitableview,cocoa-touch,ios-charts
I am working on a project where I have a table view which contains a number of cells with pretty complex content. It will be between usually not more than two, but in exceptions up to - lets say - 30 of them. Each of these complex cells contain a...

Swift: String contains Character?

string,swift,character
How do I check if a String includes a specific Character? For example: if !emailString.hasCharacter("@") { println("Email must contain at sign.") } ...

Swift - UILabel from URL

ios,swift,uilabel,nsurl
I wanted to know if it's possible to load the text in a label from a URL. I was going to try and use NSURL to pull in a .txt file stored online. Would anyone know how to implement this with swift? Thanks...

Factorials in Swift

swift,factorial
I need a good factorial function. The one I have written here works entirely, except when n gets far too large. This is for a calculator app, and I can return 0 / 0 for values that cannot be factorialed because I have an error checker that will declare that...

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

xcode,swift
I am making calculator in swift. Functioning very well so far except the display which is UILabel. I want to get clear out display by pressing C button, for that I did this way inside clear() I wrote history.text ="\0" this is caused append 0 next time when press new...

UIView within a container view not showing

ios,xcode,swift
I couldn't get the blue rectangle view to show. IT is currently the subview of the grey view and has vertical/horizontal constraints. I don't have enough "reputations" to post images so heres the link to the screenshot: http://imgur.com/gallery/KCFA1O6/new Thanks....

How to add checkbox to uicollectionview in swift

swift,checkbox,uicollectionviewcell
some time ago someone already asked this question and a few answers were given but i didn't really understand any of them. So i was wondering if anyone could please write an easy to understand tutorial on how to do the things shown on the image below: http://i.imgur.com/BzIBOkH.jpg?1 I would...

Reference method from different class as curried function

swift,methods,currying
There are two merge methods in RACSignal: - (RACSignal *)merge:(RACSignal *)signal; + (RACSignal *)merge:(id<NSFastEnumeration>)signals; When I write RACSignal.merge it references static method: class func merge(signals: NSFastEnumeration!) -> RACSignal! How to reference object method? I can't write self.merge, because it is in wrapper class and self is not RACSignal....

stringByReplacingOccurrencesOfString giving strange error

ios,swift
For some reason, this is giving me an error. swearWordPair is defined as a [String]. For example ["Hello", "Hi"] let swearWordsAndReplacements : [[String]] = [["anus", "butt"], ["arse", "butt"]] The error this gives me is Cannot invoke 'stringByReplacingOccurrencesOfString' with an argument list of type '(String, withString: String, options: NSStringCompareOptions, range: NSRange)...

startAccelerometerUpdatesToQueue Type of expression is ambiguous without more context

swift,core-motion,swift2
I am trying to translate the following code to Swift 2. manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()) { [weak self] (data: CMAccelerometerData!, error: NSError!) in self!.outputAccData(data.acceleration) } But this gives me the following error. Type of expression is ambiguous without more context Does anyone know why this is happening?...

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

ios,swift,uitableview,uiviewcontroller
In order to customize a table view and add some additional controls to it, I've embedded a UTTableViewController into a Container View and placed that container View into a UIViewController. I've followed the instructions I found here: Embedding TableView in TableViewController into another view TableView is configured with four static...

It is possible to continuously update the UILabel text as user enter value in UITextField in iOS

ios,objective-c,swift,uitextfield,uilabel
In my application i have one UILabel and UITextField. Initially UILabel text in nil. As soon as user enter some text in UITextField my UILabel text also Update. Let say When user enter A in UITextField my UILabel immediately show A, B in UITextField my UILabel show B and so...

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

iphone,swift,ios8,popup,xcode6
I am very new to ios 8 and swift but I have not found a way to make a simple popup window whenever a button is pushed. I payed for tutorials and they still don't cover it. All i would like is for when the user pushes a button (the...

Unexpectedly found nil while unwrapping an Optional value - Plist

ios,swift,plist
i am trying to read from propriety list using swift but im getting this error, and thats the code im using to read from my plist : Arrays i'm using : var recipeNames :[String] = [] var recipeImages :[String] = [] var recipeTime :[String] = [] In viewDidload : var...

Resize a UITableView

swift,uitableview,resize,frame
I have a Tableview with above it a Segmented Controller. Based on a previous user action, this segmented controller is either hidden or shown. If it's hidden, I'd like to resize my tableview, so that it looks nice (else I have an empty gap on the screen). I tried the...

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

swift,range
Is is not possible to create a range and call its contains method like this: 1...12.contains(1) When I create a var range = 1...12 and print its dynamicType I get a Swift.Range<Swift.Int>, so I'm guessing is not a type mismatch problem, or is it?...

Regular expression to get url in string swift

ios,regex,swift
I try to get urls in text. So befor I used such expression let re = NSRegularExpression(pattern: "https?:\\/.*", options: nil, error: nil)! But I had a problem, when user input urls with Capitalized symbols like it doesn't match it ( I tried let re = NSRegularExpression(pattern: "(h|H)(t|T)(t|T)(p|P)s?:\\/.*", options: nil, error:...

How to save text field value in uicollectionviewcell

swift,uitextfield,uicollectionviewcell
hi i have text field in uicollectionviewcell so what i need it example : when i edit text filed value in row 5 and i done it and go to text filed in row 20 to edit value the collectionview has reloaded and forget value in row 5, so i...

What's the equivalent of finally in Swift

swift,try-catch-finally
I try to use the error handling modeling in Swift2. do { try NSFileManager.defaultManager().removeItemAtPath("path") } catch { // ... } finally { // compiler error. } But it seems that there is no finally keyword out there.How can I achieve try-catch-finally pattern in Swift.Any help is welcome....

iOS Keyboard “Done” button load action

ios,swift,cocoa-touch
I'm trying to get "Done" button on to load an action, preferably the action that I have for my button. Here's the UITextField declaration let someTextField = UITextField() Trying to add a target to the textField someTextField.addTarget(self, action: "loginActionButton", forControlEvents: .EditingDidEndOnExit) ...

iOS Swift: Sound not playing on iPhone Simulator

ios,iphone,swift,audio,ios-simulator
In my iOS Swift application, and i am trying to play sound on click of a button. func playSound() { var audioPlayer = AVAudioPlayer() let soundURL = NSBundle.mainBundle().URLForResource("doorbell", withExtension: "mp3") audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil) audioPlayer.play() } I am running the application in iOS iPhone Simulator. I have doorbell.mp3...

Expected declaration error when adding subview

ios,swift,xcode6
Hi I got a "Expected declaration" error when I tried to add a subview to my UIView, here's the code: @IBDesignable class TimePickerView: UIView { /* // Only override drawRect: if you perform custom drawing. // An empty implementation adversely affects performance during animation. override func drawRect(rect: CGRect) { //...

Difference between stringByAppendingString and appendString in ios

ios,objective-c,swift,nsstring,nsmutablestring
What is the difference between stringByAppendingString and appendString? If NSString is not mutable then how could it append string?

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
I have SearchController for my TableViewController. I wanted to perform some actions when user taps on the empty space on the screen (between the keyboard and search bar) to dismisses the keyboard and displays the main Table View.

Parse and Swift Geopoints not saving

swift,parse.com,geopoints
I have tried everything. No matter what my Geopoints will not save when using an actual device with xcode or using the simulator. if signUpError == nil { PFGeoPoint.geoPointForCurrentLocationInBackground { (geoPoint: PFGeoPoint?, error: NSError?) -> Void in if error == nil { PFUser.currentUser()!.setValue(geoPoint, forKey: "location") } } I am not...

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

ios,swift,uialertcontroller
I have write my custom alert view controller.But,I am having error at calling my alert controller from other view controller.It show me the error that I described below. Error on console 2015-06-15 10:21:50.610 automobile[4197:62165] Warning: Attempt to present <UIAlertController: 0x7d11cf70> on <automobile.LoadingAlertViewController: 0x7bfa55d0> whose view is not in the window...

Best way to save traffic in iOS Parse App

ios,arrays,swift,parse.com,traffic
I have a logic problem in my app using Parse, Regarding which path to choose to save in traffic, and if someone has already faced a similar problem, I will really appreciate the help. Also, you can end up helping other developers facing the same problem I have a social...

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

ios,swift,parse.com
How can I update all rows with the same key value in a Parse class? As my code, I think Parse would cost a lot of my money if there are 100 objects per user. Is there any other way to do that? Thanks a lot! let username = PFUser.currentUser()?.username...

UIViewController LifeCycle

swift,uiviewcontroller,segue
I just tried some stuff using View Controller delegates and learn about their functionalities. There is one thing I would like to try: I wrote a function to unwind programmatically a viewController by using the segues. The views are inside a navigationViewController. Additionally I set a instance var inside my...

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

swift,generics
I'm trying to write a class which handles objects of a homogenous type, and I'd like to feed in those objects using an (otherwise arbitrary) Generator of the same type. In essence this: class MyGenericClass<T> { var source : GeneratorType var itemsProcessed = [ T ]() init(source: GeneratorType) { self.source...

Is this Swift syntax efficient?

ios,swift,syntax
Would this for loop fire each time the getter is accessed ? Or does Swift cache it 'behind the scenes' ? var colors: [UIColor] { get { var colors = [UIColor]() let palette = [UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor(), UIColor.orangeColor(), UIColor.purpleColor(), UIColor.yellowColor()] var paletteIndex = 0 for _ in 0..<photos.count { colors.append(palette[paletteIndex])...

Characters and Strings in Swift

ios,string,swift,unicode,character
Reading the documentation and this answer, I see that I can initialize a Unicode character in either of the following ways: let narrowNonBreakingSpace: Character = "\u{202f}" let narrowNonBreakingSpace = "\u{202f}" As I understand, the second one would actually be a String. And unlike Java, both of them use double quotes...

Do I have to use both of these methods?

ios,swift,uitableview
When I expand a UITableViewCell on touch, I know I have to update the UITableView. Right now I'm doing: tableView.beginUpdates() tableView.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: UITableViewRowAnimation.Automatic) tableView.endUpdates() Do I need to use both updates methods as well as the reload method? Or is it just one or the other? I'm not completely understanding,...

Admob interstitial ad delegate

ios,swift,admob,interstitial
I am trying to assign a delegate to admob interstitial ad so i can handle ad events. The GADInterstitialDelegate implementing class: class AdDelegate: NSObject, GADInterstitialDelegate { //Interstitial delegate func interstitial(ad: GADInterstitial!, didFailToReceiveAdWithError error: GADRequestError!) { println("interstitialDidFailToReceiveAdWithError:\(error.localizedDescription)") } func interstitialDidReceiveAd(ad: GADInterstitial!) { println("interstitialDidReceiveAd") } func interstitialWillDismissScreen(ad: GADInterstitial!) {...

compile error on FirebaseHandle

ios,swift,firebase
I got compile error when I tried to keep a reference to the handled returned by observeEventType call as suggested in the firebase iOS doc firebaseHandle = messagesRef.observeEventType(FEventType.ChildAdded, withBlock: { (snapshot) in error is: Cannot assign a value of type 'UInt' to a value of type 'FirebaseHandle!' this is the...

Parse JSON output from AlamoFire

json,swift,nsurlrequest
I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON: Alamofire.request(.GET, "*******") .responseJSON {(request, response, JSON, error) in if let statusesArray = JSON as? NSArray{ if let aStatus = statusesArray[0] as? NSDictionary{ //OUTPUT SHOWN...

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

ios,swift,nsurlsession,completion-block
OK, here's the deal: I have a URL call I'm making in a Swift app, sort of like so: /*! @brief Tests a given Root Server URL for validity @discussion What we do here, is append "/client_interface/serverInfo.xml" to the given URI, and test that for validity. @param inURIAsAString This contains...

Orientation of screen?

ios,iphone,swift,sprite-kit
How do I make sure that the only orientations allowed are Portrait or Upside down portrait? I made the change in the project settings, but I'm having trouble making the change in my GameViewController. I need to make the change in this function: override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if...

Passing String array to a function

ios,swift,nsarray
I am trying to pass an array to a function: var array:[String] = [] // fill the array array.append(uniqueId as String) // pass the array to a function: GamePrefrences.setLevelsArray(array) My function is declares like this: func setLevelsArray(arr:[String]) { GamePrefrences.levels_array = arr } But on the line i try to call...

Swift compiler macro / flag for String value alternative

swift
In Objective-C we could add a C Flag of -DVAR_NAME=@\"string value\" and then get the value with NSString *var = VAR_NAME. How do we do this in Swift? An example of this would be defining an api host based on the current git branch. Say the branch is feature1 and...

Blocking a Loop Using UIAlertController

ios,objective-c,swift,uialertcontroller
is there a way for us to block a for loop? I have a loop where inside it, it ask user with a dialog box. I would like it to pause the loop after user press OK or Cancel. Is it possible? Because looping an alertController looks really ugly especialy...

iOS 8 Swift CS193P Calculator Bug Switch Operation

ios,swift
I just started learning Swift with Stanford tutorial. I have Xcode 6.3.2. I'm getting a bug at a switch operation and can't understand how to solve it. I attached a screenshot as well @IBAction func operate(sender: UIButton) { let operation = sender.currentTitle! if userIsInTheMiddleOfTypingANumber{ enter() } switch operation{ case "➕":...

AppleScript (or swift) add hours to time

swift,date,applescript
I'm trying to add 8Hours to a date (from the clipboard) set date1 to the clipboard set newdate to date1 + (8 * hours) display dialog "Purchases were downloaded at " & newdate buttons {"OK"} default button 1 But this is not working as expected, I'm having the error Can’t...

How to get time difference based on GMT on Swift

ios,swift
I am trying to get a time difference based on a GMT time. where at the end of everyday the timer resets to zero. I've tried the below code on the Xcode simulator and every time i change the time on the mac, the difference also changes. how can i...

iAd is NOT loading with Swift

swift,iad
I have the following code. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.canDisplayBannerAds = true self.theTopAdBannerView?.hidden = false func loadAds(){ theTopAdBannerView.delegate = self theTopAdBannerView.hidden = false view.addSubview(theTopAdBannerView) } loadAds() } I made sure I linked up theTopAdBannerView outlet to...

Implementing Applovin Ads with Swift & SpriteKit

ios,swift,applovin
I would like some help with integrating interstitial ads from Applovin using Swift. Currently, I have managed to successfully integrate the SDK and initialize it using ALSdk.initializeSdk(). I have a folder in my project directory called Applovin which contains: headers folder (with all the .h files inside) and libApplovinSdk.a. I...

Beacon / IOS CLLocationManager get current region

ios,swift,cllocationmanager,ibeacon
I'm doing a program who is looking for beacon, I implemented CLLocationManager and my apps works except one point. I'm calling startMonitoringForRegion() in order to get the didEnterRegion/didExitRegion callback. Inside these function I'm doing startRangingBeaconsInRegion()/stopRangingBeaconsInRegion() in order to get precise information when the user is in the beacon area. My...

Extension function asking for return type instead of parameter

swift,uifont,swift-extensions
I am creating an extension of UIFont in Swift that will return a custom font. import UIKit extension UIFont { func museoSansRounded900(size: CGFloat) -> UIFont { return UIFont(name: "MuseoSansRounded900", size: size)! } } However, when I use the extension self.titleLabel?.font = UIFont.museoSansRounded900(15.0) Xcode returns an error in design time saying...

animating a view on top of uitableview

ios,swift,autolayout
I have a UINavigationController that has my custom ViewController with a tableView in it that takes up the whole screen. I want to push down the tableView and reveal a settings menu with just a couple items. My SettingsView.xib I created in a separate nib that is 320 x 90...

Swift SpriteKit edgeLoopFromRect Issue

ios,swift,sprite-kit,cgrect,skphysicsbody
The following code recognizes the bottom and top edges of the scene and the ball bounces off as expected. However, the left and right edges of the scene are breached all the time. The ball goes off screen and then eventually returns back if enough force is applied. It is...

Add SKShapeNode in another one

swift,sprite-kit,skshapenode
I want to draw a square in another square; but I can't position the second one in the right way. What can I do for positioning based on first square coordinates? var tileBackground = SKShapeNode(rectOfSize: CGSize(width: screenWidth, height: screenWidth)) tileBackground.name = "tileBackground" tileBackground.fillColor = SKColor.whiteColor() tileBackground.position = CGPoint(x: frame.midX, y:...

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

ios,xcode,swift,uitableview,tableviewcell
I have a table view like this: when the user tap one row, I want uncheck the last row and check the selected row. So I wrote my code like this: (for example my lastselected = 0) func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { var lastIndexPath:NSIndexPath = NSIndexPath(forRow: lastSelected, inSection:...

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

ios,arrays,swift,casting,type-conversion
I have an array that looks like this: var arr: [Int] = [1,2,3,4,5] In order to print this, I would like to convert this to: var newArr: [String?] = ["1","2","3","4","5"] Please help me out! Thanks in advance....

PFUser not unwrapped - swift

ios,xcode,swift
I'm beginning to learn swift with parse and i've run into this error: "Value of optional type 'PFUser?' not unwrapped; did you mean to use '!' or '?' I can't seem to get it to work... PFFacebookUtils.logInWithPermissions(["public_profile", "user_about_me", "user_birthday"], block: { user, error in if user == nil { println("the...

iOS 9 not opening Instagram app with URL SCHEME

ios,swift,swift2,ios9
The following URL opens on iOS 8.3 and lower, but it does not work and iOS 9 let instagramURL = NSURL(string: "instagram://app") Why won't the URL open?...

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

ios,swift,parse.com
I see that my parse login through Facebook code looks like this. PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions) { (user: PFUser?, error: NSError?) -> Void in if let user = user { if user.isNew { println("User signed up and logged in through Facebook!") let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result,...

How do I use my class in AppDelegate.swift

ios,swift,appdelegate
I have a ‘Member' class inside the project and I'm trying to pass some data from Phone to Watch extension. The error says: Use of unresolved identifier ‘Member' I tried to create a module ‘MemberKit’ and import it but I still get this eror. Thanks in advance! func application(application: UIApplication,...

AutoLayout complains about constraints for 2 UITextFields with no borders

ios,xcode,swift,autolayout,nslayoutconstraint
I am trying to build my login view that has only 2 TextFields, and 2 buttons. I am applying the "Add Missing Constraints" property so that Xcode applies the corresponding constraints to all the elements in my LoginViewController in the storyboard. I am restricting my app to run only in...

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

ios,swift,ios8,uiimagepickercontroller,ios8.3
- Actually am using UIImagePickerController for my usecase,and if i long press any picture ,it shows Copy/Hide option (as shown in the sample image) - I dont want the Copy/Hide feature. Guide me with some suggestions if u too have encountered :)... Thanks in advance...iOS Geeks...PLZ refer my code snippet...

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

ios,iphone,swift
I think the question is pretty straightforward. I need only the date to appear, and not the time. Couldn't find anything for Swift, so my code is here: cell.date.text = NSDateFormatter.localizedStringFromDate(dates[indexPath.row], dateStyle: .ShortStyle, timeStyle: .ShortStyle) ...

coordinate deprecated as of iOS 7

ios,iphone,swift
I am trying to grab the latitude and longitude of a users location. I have a code which worked prior to deprecation, and I cannot figure out how to fix it. The error is on the coordinate section of latestLocation.coordinate.latitude and latestLocation.coordinate.longitude, and the error states: 'coordinate' is unavailable: APIs...

Get NSString from NSMutableArray on Swift

swift,nsmutablearray
How can I get NSString from NSMutableArray created with NSStrings in a for loop? I want to store in one NSString, all elements of NSMutableArray. This is my code: class Persona: NSObject { var edad: Int var altura: Double var nombre: NSString var apellido: NSString var cualidades: NSMutableArray init(edad:Int, altura:Double,...

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

ios,swift,uistoryboard,xcode7
I don't use a storyboard/xib for launch screen and get this error in XCode7 / Swift2.0.

looping variable in swift

swift,for-loop,uiimage
i want to change this variable become looping in swift: var image1 = UIImage(named: "image1") var image2 = UIImage(named: "image2") var image3 = UIImage(named: "image3") var image4 = UIImage(named: "image4") var image5 = UIImage(named: "image5") var image6 = UIImage(named: "image6") var image7 = UIImage(named: "image7") images.append(image1!) images.append(image2!) images.append(image3!) images.append(image4!) images.append(image5!)...

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

ios,swift
This question already has an answer here: ?? operator in Swift 3 answers I have seen such function: public func highlightValues(highs: [ChartHighlight]?) { // set the indices to highlight _indicesToHightlight = highs ?? [ChartHighlight](); // redraw the chart setNeedsDisplay(); } What's the purpose of ?? here? I searched, but...

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

ios,objective-c,swift,storyboard,segue
How can I do a "show (e.g Push)" segue programatically without animation? None of the solutions I've found works the same way as the one in storyboard.

Chance of a conditional occurring in Swift: Xcode

xcode,swift,if-statement,conditional,percentage
I am quite new to Xcode and swift so sorry if this is a bad description. Is there a way that there is a chance of your conditional occurring so instead of it happening 100% of the time when the conditions are met, it only happens 50% of the time...

Swift timer in milliseconds

xcode,swift
I want to change the timer every millisecond but it doesnt work as expected. NSTimer.scheduledTimerWithTimeInterval(0.001, target: self, selector: Selector("advanceTimer:"), userInfo: nil, repeats: true); func advanceTimer(timer: NSTimer){ self.time += 0.001; let milliseconds = self.time * 100; let remaingMilliseconds = Int((milliseconds % 1000) / 10); let seconds = Int((milliseconds / 1000) %...

Detect UIImageView Touch in Swift

ios,swift,uiimageview
How would you detect and run an action when a UIImageView is touched? This is the code that I have so far: override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { var touch: UITouch = UITouch() if touch.view == profileImage { println("image touched") } } ...

Build error after I localized Info.plist

ios,objective-c,xcode,swift,localization
I localized Info.plist : And I got this build error : error: could not read data from '/Users/cherif/Apps/Wesh/Info.plist': The file “Info.plist” couldn’t be opened because there is no such file. Actually there are now two Info.plist files : fr.lproj/Info.plist Base.lproj/Info.plist How to localize the Info.plist path ?...

Stop async operations on window close

swift,cocoa,appdelegate
In my app delegate I have put the callback to stop the program when the window is shut. func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool { return true } This doesn't work however because (I assume) there is an async bluetooth task running. What is the best way to stop everything running...