w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » SWIFT » Page 1
using Swift to get contents of URL using session.dataTaskWithRequest() - data doesn't convert to NSString
It looks like it should be fine, to me at least. I'm just dabbling in Swift, but I've done my enclosures (not sure if thats the right name) slightly changed like below. Did you try converting data to NSString prior to your if let httpRes = response as? NSHTTPURLResponse line? Maybe the data variable doesn't actually have the html in it. I have code written almost exactly the same with the chan

Categories : Swift

performSegue after completion handler
To solve this problem you just need to create your segue from your viewController1 to your viewController2 and not from a button. This way you can trigger prepareForSegue programatically using the "performSegue" method that will call prepareForSegue anyway.

Categories : Swift

Swift - nil checking an NSCopying function argument
I assume that you can use the same workaround that is documented in the Xcode 6.1 Release Notes for methods, properties, or initializers for which the return value is incorrectly considered non-nullable: let identOpt : NSCopying? = identifier if let ident = identOpt { } Even better you can actually change the methods signature replacing NSCopying with NSCopying?: func collisionBehavior(behav

Categories : Swift

error: missing argument for parameter #1 in call (swift)
The function you are trying to call has this signature: func swipedRight1(sender:UISwipeGestureRecognizer) but you are calling it with no parameters: scene.swipedRight1() just pass it the expected parameter, which in this case it's the same sender you have in the calling method: scene.swipedRight1(sender)

Categories : Swift

How do I animate opacity using swift?
If you need a simple animation, why not just use UIView's animateWithDuration:animations: method? imageView.alpha = 0 UIView.animateWithDuration(1.0) { imageView.alpha = 1 }

Categories : Swift

Detect what is the location of the tap/press inside UIButton inside sender action method
Create the action function with sender and event params. Then you can get the touch location on the button. @IBAction func buttonAction(sender: AnyObject, event: UIEvent) { // downcast sender as a UIView let buttonView = sender as UIView; // get any touch on the buttonView if let touch = event.touchesForView(buttonView)?.anyObject() as? UITouch { // print the touch locat

Categories : Swift

in swift how to dismiss the key board
You need to have a reference to the UITextField so make a property value like this class MyClass: UIViewController { var textBox1: UITextField! ... // create your textfield where ever you were by assigning it to self.textBox1 } Then to dismiss the keyboard you resign its as the first responder. self.textBox1.resignFirstResponder() Update to dimiss keyboard Dismissing on return/done w

Categories : Swift

NSValue to CLLocationCoordinate2D in Swift
I think, getBytes:length: from NSData would be sufficient: var locationData = entry.fields["location"] as NSData var locationCoord = CLLocationCoordinate2D(latitude: 0, longitude: 0) locationData.getBytes(&locationCoord, length: sizeof(CLLocationCoordinate2D)) BTW, Why your code doen't work? That is: objCType: parameter is not expecting a type name "String", but expecting "Type Encodings

Categories : Swift

MKPointAnnotations touch event in swift
Several steps are necessary, here are some code snippets to get you started. First you need a custom class for your pin annotation which holds the data you want to work with. import MapKit import Foundation import UIKit class PinAnnotation : NSObject, MKAnnotation { private var coord: CLLocationCoordinate2D = CLLocationCoordinate2D(latitude: 0, longitude: 0) var coordinate: CLLocationC

Categories : Swift

SWIFT iOS8 Alamofire how to build following POST request
All typed properties are content-headers of your HTTP(S?) request. Here is the solution: let headers = [ "Connection": "keep-alive", "Content-Length": "104", "Cache-Control": "max-age=0", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8", "Origin": "URL", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (

Categories : Swift

Is it possible to change an enum from inside an enum method?
When you're going to modify a value type (i.e., struct or enum) in a method, you need to mark it as mutating. This will make the method usable by mutable instances (declared with var ...) but not immutable instances (let ...): mutating func rotate(clockwise: Bool) { var nextRawValue = self.rawValue + (clockwise ? 1 : -1) if nextRawValue < Orientation.Rot_0.rawValue { nextR

Categories : Swift

Correct transition of subviews in UICollectionViewCell
I solved the issue by using TLTransitionLayout for transitioning to the other layout. It makes the animation look better for more complex cells, because it is not using Core Animation. The approach is also compatible to useLayoutToLayoutNavigationTransitions, so you get all the nice stuff like a new navigation item pushed to the navigation bar etc. (I only tested on iOS8 though). So these were m

Categories : Swift

Getting a readable time from timeIntervalSinceDate in swift
Fix your syntax. It should be: var totalWorkTime = NSDate().timeIntervalSinceDate(punchInTime) Note the parenthesis after NSDate. If you do not use parenthesis, and you try to treat totalWorkTime as an NSTimeInterval you will get the error Cannot invoke [operator] with an argument list of type ... You can get a better error message if you specify the type in the variable assignment. The erro

Categories : Swift

Checking bitmask in Swift
keyEquivalentModifierMask is a Int, whereas NSEventModifierFlags.CommandKeyMask is an enum-like with UInt raw value, so you have to read the rawValue out of it and convert keyEquivalentModifierMask to Uint: if UInt(button.keyEquivalentModifierMask) & NSEventModifierFlags.CommandKeyMask.rawValue > 0 { }

Categories : Swift

Why would Xcode not find my customized UICollectionViewCell?
I think this is a bug in XCode, I've run into it for no reason, and had it start working later on. The work around is to type out your outlet in the swift file first: @IBOutlet weak var imageView:UIImageView! Then compile and drag from the swift file to interface builder.

Categories : Swift

Keychain doesn't work when installing app using TestFlight
You should check the console on the device you are unable to access the keychain on and look for logs indicating an issue with keychain access. This sounds like an issue with entitlements. Check out this FAQ on how to address the issue you will probably see in the console: https://developer.apple.com/library/ios/qa/qa1726/_index.html EDIT I think you are probably not filling out all of the nece

Categories : Swift

Swift spritekit set userdata
The first argument in a method does not have an external parameter name, therefore it should be p.userData?.setValue("Hello", forKey: "c") or better (since userData is a NSMutableDictionary and no Key-Value Coding magic is required here): p.userData?.setObject("Hello", forKey: "c") Note also (as just mentioned in a comment) that you have to create the dictionary first: p.userData = NSMutabl

Categories : Swift

iOS 8: Storyboard - Delegate for UIPopoverController
Had the same issue recently. In iOS 8, you can access the UIPopoverPresentationController and set the UIPopoverPresentationControllerDelegate (rather than the UIPopoverController and -Delegate) through the popoverPresentationController of the destinationViewController, using this code: override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) { if let controller = segue.des

Categories : Swift

Swift array subscript extension "Range is not convertible to Int"
Because Array already have subslice functionality: typealias SubSlice = Slice<T> subscript (subRange: Range<Int>) -> Slice<T> So, in order to your implementation work, you have to explicitly specify the return type: let a = [4, 3, 2, 1, 0, -1][2..<4] as S<Int>

Categories : Swift

'UIStoryboard.type' does not have member named 'centerViewController'
You are missing the extension the tutorial author has provided that makes the UIStoryboard.centerViewController() method exist. The code is at the bottom of ContainerViewController.swift in his downloadable starter project, and I've copied it down below as well: private extension UIStoryboard { class func mainStoryboard() -> UIStoryboard { return UIStoryboard(name: "Main", bundle: NSBundle.m

Categories : Swift

Is there an equivalent for respondsToSelector to check if a variable exists?
You can check if the variable exists by looking at the address of the variable: if (&UIApplicationOpenSettingsURLString != nil) { // UIApplicationOpenSettingsURLString exists } else { // don't use UIApplicationOpenSettingsURLString }

Categories : Swift

View navigations in Swift
Here is the sample code for navigation from rootViewController to SecondViewController: let secondViewController : SecondViewController = self.storyboard?.instantiateViewControllerWithIdentifier("View2") as SecondViewController self.navigationController?.pushViewController(secondViewController, animated: true) Put this code where you want to perform this action also dont forget to create Second

Categories : Swift

How do you access a UIViewController function from within a UICollectionCell?
This is a mildly controversial question - the answer depends a little on your philosophy about MVC. Three (of possibly many) options would be: Move the @IBAction to the view controller. Problem solved, but it might not be possible in your case. Create a delegate. This would allow the coupling to be loose - you could create a ContributionDelegate protocol with the makeContribution() method, make

Categories : Swift

Swift: Button Enabling Not Working?
Your delegate methods are a bit mixed up -- they have to be named exactly what the caller expects, or they won't be found, so yourWeightTextFieldValueValidInt() and calorieNumberTextFieldValueValidInt() aren't being called at all. Instead you'll need to handle the edits to both text fields in a single method: func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, rep

Categories : Swift

Curried infix operators in swift. Is it possible?
Let's write some (incomplete) definitions for the terms in your question: non-curried two-argument function: A function that takes two arguments and returns some value. Example: func add(a: Int, b: Int) -> Int curried two-argument function: A function that takes one argument and returns another function that takes one argument and returns some value. Example: func add(a: Int)(b: Int) -> In

Categories : Swift

Adding swift file to new view controller in xCode? (easy)
Add a new Cocoa Touch class. Choose File->New->File... from the menu. Give this new class a name such as "ViewController2" and set the Subclass of: pop down to UIViewController. The file "ViewController2.swift" will be created. Click on your new View Controller in Interface Builder. In the Identity Inspector (on the right in Xcode) set the Custom Class for the View Controller to

Categories : Swift

Call methods on Protocol Type
Class methods are only allowable in classes and protocols; an enum is neither. Class methods are one type of Swift "type methods"; the other type is a static method, which is what you've declared in your enum. Class and static methods are different. See the Swift methods docs for a few different patterns and examples. p.s. it says the last call is unimplemented, so should I expect it in a fu

Categories : Swift

Button perform action from another file (Swift)
If you want your button actions to be in a different Swift file, just create a class extension for your ViewController in the new file: ViewController.swift import UIKit class ViewController: UIViewController { @IBOutlet weak var myTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from

Categories : Swift

iOS8 Swift custom-keyboard button UIimage size problems
The problem is written in the log: Unable to simultaneously satisfy constraints. ... ( "<NSLayoutConstraint:0x1700913f0 'UIView-Encapsulated-Layout-Height' V:[UIInputView:0x13f5091e0(216)]>", "<NSLayoutConstraint:0x170091d00 V:[UIInputView:0x13f5091e0(100)]>" ) You're probably setting the height using Autolayout in the Storyboard (or any other place in the code). Just r

Categories : Swift

How can I make a button have a rounded border in Swift?
Use button.layer.cornerRadius, button.layer.borderColor and button.layer.borderWidth. Note that borderColor requires a CGColor, so you could say for example: button.backgroundColor = UIColor.clearColor() button.layer.cornerRadius = 5 button.layer.borderWidth = 1 button.layer.borderColor = UIColor.blackColor().CGColor

Categories : Swift

Replicate the default button back segue from a table view clel
Just for future reference I found that this is what I was looking to do: func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { println("did select") if let navController = self.navigationController { navController.popViewControllerAnimated(true) } }

Categories : Swift

Time difference between button presses swift
You should give your ViewController class a ref to a TimeLog class (why did you choose a struct? works too but just curious). var timeLog: TimeLog? Second of all you want to initialise it with a fresh one every time you punch in @IBAction func punchInButtonPressed(sender: AnyObject) { let now = CFAbsoluteTimeGetCurrent() self.timeLog = TimeLog(pInTime: now) } So you initialise only w

Categories : Swift

JavaScriptCore and Swift "this class is not key value coding-compliant for the key test"
You're using the wrong method. You want to use setObject:forKeyedSubscript: from JSContext and not setValuesForKeysWithDictionary: from the NSKeyValueCoding protocol (which JSContext does not conform to) i.e. : let context = JSContext() let label = SKLabelNode(text:"Test") context.setObject(label, forKeyedSubscript: "test")

Categories : Swift

Swift Spritekit setvalue
To use setValue:forKey: you need to have (a) a valid key, and (b) a value of the correct type for that key. For example: mySprite.setValue(UIColor.redColor(), forKey: "co") // error, "co" isn't a valid key mySprite.setValue("red", forKey: "color") // error, "color" needs a UIColor value mySprite.setValue(UIColor.redColor(), forKey: "color") // works! What value and key are you act

Categories : Swift

Objects saved with NSKeyedArchiver and loaded back are nil
You need to save and retrieve all the attributes of Bottle in the NSCoding methods: required init(coder aDecoder: NSCoder) { self.bottlesArray = aDecoder.decodeObjectForKey("bottleArray") as NSMutableArray self.id = aDecoder.decodeObjectForKey("id") as String //etc. same for title, year, and icon (use decodeIntegerForKey: for year) } func encodeWithCoder(aCoder: NSCoder) { aCoder

Categories : Swift

Changing NavigationBar and System Colors Without Tint
Navigation bars are translucent by default, you need to turn that off, then use barTintColor to change the background of the navigation bar: UINavigationBar.appearance().translucent = false UINavigationBar.appearance().barTintColor = UIColor.redColor() Setting the background color changes the semi-gross color underneath a translucent bar - you don't need that.

Categories : Swift

How to append something like ?id=1 to a NSMutableURLRequest
The problem is that the question mark in ?timeFrame=n14 is treated as part of the URL's path and therefore HTML-escaped as %3F. This should work: let baseUrl = NSURL(string: "http://www.football-data.org")! let url = NSURL(string: "soccerseasons/" + "(league.id)" + "/fixtures?timeFrame=n14", relativeToURL:baseUrl)! let request = NSMutableURLRequest(URL: url) Alternatively, use NSURLComponents,

Categories : Swift

Changing the Status Bar Color for specific ViewControllers using Swift in iOS8
Implement preferredStatusBarStyle as you mentioned and call self.setNeedsStatusBarAppearanceUpdate() in ViewDidLoad and also in Info.plist set UIViewControllerBasedStatusBarAppearance to YES (It's YES by default) It is not clear why it is not working.I need to check code.One other suggestion is go with working code in viewDidLoad UIApplication.sharedApplication().statusBarStyle = .LightConten

Categories : Swift

Swift: how do you understand this function signature: func curry(f: (A, B) -> C) -> A -> B -> C
It's a function that takes one parameter of type (A, B) -> C (that is function taking two arguments and returning one) and returns A -> B -> C (that is, A -> (B -> C) i.e. function that takes one argument and returns function B -> C). Currying "breaks" two argument function into two steps. Currying two argument function yields single argument function that returns another single

Categories : Swift




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.