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...
[collectionView setShowsHorizontalScrollIndicator:NO]; [collectionView setShowsVerticalScrollIndicator:NO]; ...
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. ...
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...
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"));...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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...
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.
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"...
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:...
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...
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:...
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...
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...
lower the quality/bitrate of the audio that you play.
I use this approach [NSApp performSelector:@selector(terminate:) withObject:nil afterDelay:0]; ...
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,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); } -...
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...
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...
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,...
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...
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 } }...
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) } ...
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:...
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...
Use CGFloat not Float Check the API docs when you get an error like this...
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...
swift,checkbox,uicollectionviewcell
Here is the example project available with checkbox cell. (objective - c) MyCell.m // A setter method for checked property - (void)setChecked:(BOOL)checked { // Save property value _checked = checked; // Update checkbox image if(checked) { self.checkBoxImageView.image = [UIImage imageNamed:@"Checked"]; } else { self.checkBoxImageView.image = [UIImage imageNamed:@"Unchecked"]; } } Your...
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...
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...
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...
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() } } ...
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....
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...
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 =...
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....
Replace the following in your code var latestLocation: AnyObject = locations[locations.count - 1] with the following. var latestLocation = locations.last as! CLLocation ...
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...
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{...
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...
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{...
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...
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.
The method observeEventType returns a Uint ( UInt8 actually ). So your firebaseHandle variable should be defined like that : var firebaseHandle: UInt8 = 0 Hope it helps....
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!...
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...
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...
var dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" dateFormatter.locale = NSLocale(localeIdentifier: @"en_US") let d = NSDate() let s = dateFormatter.stringFromDate(d) ...
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...
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...
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...
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.
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,...
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...
How about -searchBarTextDidEndEditing: in UISearchBarDelegate?
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 ... ...
Apparently my ad wasn't loading. All of a sudden it loads fine now.
The Range is not an NSRange, but a Swift range. In this case, you can pass nil to represent the entire String: string = string.stringByReplacingOccurrencesOfString(swearWordPair[0], withString: swearWordPair[1], options: .CaseInsensitiveSearch, range: nil) If you wanted to limit the range, you can create a Range<String.Index> like this: var string = "I laid...
When the "Return Key" (or "Done") button is tapped, the delegate of your textfield will receive a set of callbacks including textFieldShouldEndEditing:, and textFieldDidEndEditing:. To respond to these, implement a UITextFieldDelegate and execute your action there, i.e. call loginActionButton in one of the delegate methods. Relevant Documentation: https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/#//apple_ref/occ/intfm/UITextFieldDelegate/textFieldDidEndEditing:...
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 ...
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...
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...
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....
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() } } ...
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...
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...
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....
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...
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...
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_ ...
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...
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...
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...
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)") } ...
ios,objective-c,xcode,swift,localization
Roll back those changes, add a InfoPlist.strings file to your project, localize it and then add the needed keys to it. For example: "CFBundleDisplayName" = "App display name"; "CFBundleName" = "App bundle name"; ...
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...
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:...
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...
In this case the problem was that of operator precedence: (1...12).contains(1) // -> true (the code does look ambiguous otherwise)...
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...