Swift: Add basic HTTPAuth to NSURLSession

First you need to make sure that you use a different NSURLSessionConfiguration, where you will modify the headers.
The HTTP Auth needs to be like “Basic: base64 string”, the base64 string being the encoding of username:password.

let userPasswordString = "\(email):\(password)"
            let userPasswordData = userPasswordString.dataUsingEncoding(NSUTF8StringEncoding)
            let base64EncodedCredential = userPasswordData!.base64EncodedStringWithOptions(nil)
            let authString = "Basic \(base64EncodedCredential)"
            
            sessionConfiguration.HTTPAdditionalHeaders = ["Authorization" : authString]
Read More

Swift: Persisting and loading data from NSUserDefaults

To save data to NSUserDefaults:

@IBAction func saveDataClicked(sender: AnyObject) {
 
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

defaults.setObject(self.firstNameTextField.text, forKey: "firstName")
defaults.setObject(self.lastNameTextField.text, forKey: "lastName")
defaults.setObject(self.emailTextField.text, forKey: "email")
defaults.setObject(self.phoneNumberTextField.text, forKey: "phoneNumber")

defaults.synchronize()
 
 }

To load data from NSUserDefaults:

@IBAction func loadDataClicked(sender: AnyObject) {
 
 var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()

 if let firstNameIsNotNill = defaults.objectForKey("firstName") as? String {
 self.firstNameTextField.text = defaults.objectForKey("firstName") as String
 }
 
if let lastNameIsNotNill = defaults.objectForKey("lastName") as? String {
 self.lastNameTextField.text = defaults.objectForKey("lastName") as String
 }
 
if let emailIsNotNill = defaults.objectForKey("email") as? String {
 self.emailTextField.text = defaults.objectForKey("email") as String
 }
 
if let phoneNumberIsNotNill = defaults.objectForKey("phoneNumber") as? String {
 self.phoneNumberTextField.text = defaults.objectForKey("phoneNumber") as String
 }

 }
Read More

Swift: Loop through the view controllers of a TabBar

        if let viewControllers = self.viewControllers {
            for viewController in viewControllers {
                if let viewControllerContainer = viewController as? ContainerViewController {
                    println("found")
                }
            } 
        }
Read More

Swift: Change transparency of UINavigationBar

self.navigationBar.setBackgroundImage(UIImage(), forBarMetrics: UIBarMetrics.Default)
self.navigationBar.shadowImage = UIImage()
self.navigationBar.translucent = true

Setting translucent to YES on the navigation bar does the trick, due to a behaviour discussed in the UINavigationBar documentation. I’ll report here the relevant fragment:

If you set this property to YES on a navigation bar with an opaque custom background image, the navigation bar will apply a system opacity less than 1.0 to the image.

Read More

Swift: navigationItem mistery

Why is self.navigationController.navigationItem and self.navigationItem different?

self.navigationController.navigationItem is useless since it is accessing navigation item of the navigation controller (i.e. your rootViewController). What you really want is self.navigationItem, navigation item of the view controller because that is what essentially going to show up in your view controller.

UINavigationController is a subclass of UIViewController so self.navigationController.navigationItem is just a spillover method from subclassing. It does not do anything positive.

Read More

Swift: Create a simple enum type

Defining an enum is simple, to do so write the enum type, then the possible values:

enum SomeState {
        case State1
        case State2
        case State3
    }

To use the enum in code:

var myViewIsInState: SomeState = .State1
Read More

Swift: About optional values and unwrapping them

What does it mean to “unwrap the instance”? Why is it necessary?
The term “wrapped” implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty.

When “wrapped”, the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)), or not (None).

If there is a value, this can be obtained by “unwrapping” the variable (obtaining the T from Some(T)).

How is john!.apartment = number73 different from john.apartment = number73?

If you write the name of an Optional variable (eg text john, without the !), this refers to the “wrapped” enum (Some/None), not the value itself (T). So john isn’t an instance of Person, and it doesn’t have an apartment member:

john.apartment
// ‘Person?’ does not have a member named ‘apartment’
The actual Person value can be unwrapped in various ways:

“forced unwrapping”: john! (gives the Person value if it exists, runtime error if it is nil)
“optional binding”: if let p = john { println(p) } (executes the println if the value exists)
“optional chaining”: john?.learnAboutSwift() (executes this made-up method if the value exists)
I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case).

The exclamation mark is also used in the syntax for declaring “Implicitly Unwrapped Optionals”.
In the examples so far, the john variable has been declared as var john:Person?, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above.

If it were declared as var john:Person! instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple’s book). There is no need to unwrap this kind of variable when accessing the value, and john can be used without additional syntax. But Apple’s book says:

Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable.

 

An optional in Swift is a variable that can hold either a value or no value. Optionals are written by appending a ? to the type:

var myOptionalString:String? = “Hello”
From “The Basics” in the Swift Programming Language:

Swift also introduces optional types, which handle the absence of a value. Optionals say either “there is a value, and it equals x” or “there isn’t a value at all”. Optionals are similar to using nil with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil pointers in Objective-C and are at the heart of many of Swift’s most powerful features.

Optionals are an example of the fact that Swift is a type safe language. Swift helps you to be clear about the types of values your code can work with. If part of your code expects a String, type safety prevents you from passing it an Int by mistake. This enables you to catch and fix errors as early as possible in the development process.

Some places optionals are useful:

When a property can be there or not there, like middleName or spouse in a Person class
When a method can return a value or nothing, like searching for a match in an array
When a method can return either a result or get an error and return nothing
Delegate properties (which don’t always have to be set)
For weak properties in classes. The thing they point to can be set to nil
For a large resource that might have to be released to reclaim memory
You can use an optional as a Boolean type in an if or while statement. Here’s an example of creating an optional, then checking for its existence:

var myString:String? = “Hello”

if myString {
println(myString)
}
If you try to do this using a non-optional type it will give a compiler error: “Type ‘String’ does not conform to protocol ‘LogicValue'”

var myOtherString:String = “Hello”

if myOtherString { // Error
println(myOtherString)
}
Also, if you try to set a non-optional to nil you get the error “Could not find an overload for ‘__conversion’ that accepts the supplied arguments”:

var myOtherString:String = nil // Error
If a variable is declared as an optional, it can be nil. In fact all optionals start with a value of niluntil they are set to something:

var possibleString:String? = “Hello”
possibleString = nil

if possibleString {
println(“It’s not nil”)
}
Here’s one way to use optionals:

var nameString:String? = “Zed” // could also be nil

if nameString {
println(“\(nameString)’s alive”)
} else {
println(“Zed’s dead”)
}
You can use optionals for checking the existence of a value in a dictionary:

let users = [ “sjobs” : “Steve Jobs”, “bgates” : “Bill Gates”]

let steve: String? = users[“sjobs”]
if steve { // if steve != nil
println(“\(steve) is in the dictionary”)
}
There’s a shorthand for checking whether a value exists, then doing something with it. You can convert from this style:

let possibleName: String? = users[“ballmer”]

if possibleName {
let foundName = possibleName! // Force out value with unwrap operator (!)
println(“Name: \(foundName)”)
}
…to this shorthand, which says “If possibleName has a value, unwrap it and set its value to foundName.

if let foundName = possibleName {
println(“Name: \(foundName)”)
}
You use an exclamation mark “!” to unwrap the optional. You can’t use an optional for much (except checking its nilness) until it’s unwrapped. Note that unwrapping an optional that’s nil will cause a crash. Always check that a value exists before unwrapping:

// Crash: fatal error: Can’t unwrap Optional.
let name = possibleName!
More from the Swift guide:

In an if statement, the conditional must be a Boolean expression—this means that code such as if score { … } is an error, not an implicit comparison to zero.

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

It may be helpful to see the same thing in Objective-C:

NSString *myString = @”Hello”;
if (myString) {
NSLog(@”%@”, myString);
}
Objective-C is more lenient about what it will allow to mean “false” (NO, 0, nil). Swift is more restrictive and wants a boolean (or something which “unwraps” to a boolean). Using optionals also gets rid of the need for stuff like NSNotFound and using -1 to represent false.

Sources: http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language

http://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift

Read More

Swift: Shorthand external parameter name

If you want to mark a parameter with the same name as the external parameter name, then specify a “#” character in front of it.

For example, in case you would not specify an external parameter name, nor a “#” character, you could call a function like:

loadItem("some string", image: "someImage.jpeg") 

But what is the first argument there?

If you want to make sure that it refers to the title, then mark this parameter in the function definition accordingly.

loadItem(title: "some title", image: "someImage.jpg")

e.g.

    func loadItem(#title: String, image: String) {
        backgroundImage.image = UIImage(named: image)
        titleLabel.text = title
    }

f you want to provide an external parameter name for a function parameter, and the local parameter name is already an appropriate name to use, you do not need to write the same name twice for that parameter. Instead, write the name once, and prefix the name with a hash symbol (#). This tells Swift to use that name as both the local parameter name and the external parameter name.

Read More

Swift: Instantiate a view controller from another storyboard

1. Make sure you create a new storyboard with name (filename) as StoryboardName
2. Create a new view controller and give Storyboard ID as InitialController

        var storyboard = UIStoryboard(name: "StoryboardName", bundle: nil)
        var controller = storyboard.instantiateViewControllerWithIdentifier("InitialController") as! UIViewController
        
        self.presentViewController(controller, animated: true, completion: nil)
Read More

Swift: Tricks to create a padding like effect in an UITextField

self.myTextField.layer.sublayerTransform = CATransform3DMakeTranslation(5, 0, 0);

or

In a class derived from UITextField, override at least this two methods:

- (CGRect)textRectForBounds:(CGRect)bounds;
- (CGRect)editingRectForBounds:(CGRect)bounds;

It might be as simple as this if you have no additional content:

return CGRectInset( bounds , 10 , 10 );
Read More