Thursday, April 28, 2016

Facebook SDK and Swift - Create a custom login button programmatically

The FBSDKLoginButton style is like this:


To create a custom Facebook login button, follow these two tutorials first:

Facebook SDK and Swift - Create a Facebook Login Button
Facebook SDK and Swift - Display User Name and Profile Picture

Then remove the FBSDKLoginButton and create a UIButton instead. Add this to viewDidLoad()with Xcode 7.3 (Swift 2.2):


let btnSize : CGFloat = 100
let btnLogin = UIButton(frame: CGRectMake(0,0,btnSize,btnSize))
btnLogin.center = CGPoint(x: view.center.x, y: 400)
btnLogin.setImage(UIImage(named: "facebook_logo.png"), forState: UIControlState.Normal)
btnLogin.addTarget(self, action: #selector(btnLoginPressed), forControlEvents: UIControlEvents.TouchUpInside)
        
//Circular button
btnLogin.layer.cornerRadius = btnSize/2
btnLogin.layer.masksToBounds = true
btnLogin.layer.borderColor = UIColor.blackColor().CGColor
btnLogin.layer.borderWidth = 2

view.addSubview(btnLogin)

and then add this:

func btnLoginPressed() {

let loginManager = FBSDKLoginManager()
loginManager.logInWithReadPermissions(["public_profile"], fromViewController: self, handler: { (response:FBSDKLoginManagerLoginResult!, error: NSError!) in
    if(error == nil){
        print("No Error")
        self.getFacebookUserInfo()
        }
    })
}

Result:


Related Information:

Google Sign-In for iOS - Create a custom sign-in button programmatically

Google Sign-In for iOS - Create a custom sign-in button programmatically

The GIDSignInButton can be assigned as one of the following styles (See GIDSignInButton Class):

GIDSignInButtonStyle.Standard => 230x48


GIDSignInButtonStyle.Wide     => 312x48


GIDSignInButtonStyle.IconOnly =>  48x48

However, we may need custom styles other than the above sign-in buttons. For example the 48x48 IconOnly style is a bit small on the screen and hence we want to enlarge it. So the code below shows how to implement a custom Google sign-in button with these properties:


  • Custom image
  • Custom button size
  • Circular shape

To get started, implement a standard Google Sign-In button with instructions in this tutorial:

Google Sign-In for iOS - Create a GIDSignInButton programmatically in Swift

Then remove the GIDSignInButton and add a UIButton instead:


    var btnSignIn : UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        ...
        
        let btnSize : CGFloat = 100
        btnSignIn = UIButton(frame: CGRectMake(0,0,btnSize,btnSize))
        btnSignIn.center = view.center
        btnSignIn.setImage(UIImage(named: "google_logo.png"), forState: UIControlState.Normal)
        btnSignIn.addTarget(self, action: #selector(btnSignInPressed), forControlEvents: UIControlEvents.TouchUpInside)

        //Circular button
        btnSignIn.layer.cornerRadius = btnSize/2
        btnSignIn.layer.masksToBounds = true
        btnSignIn.layer.borderColor = UIColor.blackColor().CGColor
        btnSignIn.layer.borderWidth = 2
        view.addSubview(btnSignIn)

        ...
    }
    
    func btnSignInPressed() {
        GIDSignIn.sharedInstance().signIn()
    }

Result:


Related Information:

Facebook SDK and Swift - Create a custom login button programmatically

Wednesday, April 27, 2016

Asynchronously Display an Web Image with NSURLSession.sharedSession().dataTaskWithURL

To display an image on the Internet in Swift 2.2 with Xcode 7.3 using asynchronous download method, modify ViewController.swift as:

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let url = NSURL(string: "https://....JPG")!
        
        let imageSize : CGFloat = 200
        let imageView = UIImageView(frame: CGRectMake(0, 0, imageSize, imageSize))
        imageView.center = view.center
        
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
            
            if let error = error {
                print("Image read error \(error)")
                return
            }
            
            imageView.image = UIImage(data: data!)
        }).resume()
        
        //Synchronous Method without using NSURLSession
        //imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
        
        //Scale the image with the original aspect ratio
        imageView.contentMode = UIViewContentMode.ScaleAspectFit
        
        view.addSubview(imageView)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Google Sign-In for iOS - Get User Name, Email and Profile Picture without Nofitication

Previously, I have worked out how to implement a Google Sign-In button and display the user email and profile picture in these posts:

Google Sign-In for iOS - Create a GIDSignInButton programmatically in Swift
Google Sign-In for iOS - Display User Email and Profile Picture

When the user is just signed in with the two examples above, AppDelegate.swift posts a notification including the user information and then ViewController.swift receives the user information in the receiveToggleAuthUINotification function.

However, I need to separate the sign-in button and the display of the user information in two different view controllers. The view controller to show the user information is displayed AFTER signed in and hence the notification is unable to be detected. The solution is to include the code below:

if (GIDSignIn.sharedInstance().hasAuthInKeychain()) {
    print("signed in")
    print(GIDSignIn.sharedInstance().currentUser.profile.email)
    print(GIDSignIn.sharedInstance().currentUser.profile.name)
    print(GIDSignIn.sharedInstance().currentUser.profile.imageURLWithDimension(100))
}

Related Information:

Google Sign-In for iOS - Create a GIDSignInButton programmatically in Swift
Google Sign-In for iOS - Display User Email and Profile Picture

Monday, April 25, 2016

Customize UIToolbar with text, textfield, button and fixed/flexible gaps

The code below shows how to customize a UIToolbar with a fixed gap, a flexible space, a text, a textfield, and a button. The code is written in Swift 2.2 with Xcode 7.3.

Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController, UITextFieldDelegate {
    
    var textField : UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //Fixed space
        let fixed = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FixedSpace, target: self, action: nil)
        fixed.width = 10
        
        //Text
        let text = UIBarButtonItem(title: "My Title", style: UIBarButtonItemStyle.Plain, target: self, action: nil)
        text.setTitleTextAttributes([
            NSFontAttributeName : UIFont.systemFontOfSize(23.0),
            NSForegroundColorAttributeName : UIColor.whiteColor()], forState: UIControlState.Normal)
        
        //TextField
        textField = UITextField(frame: CGRectMake(0,0,150,30))
        textField.delegate = self
        textField.textColor = UIColor.blueColor()
        let border = CALayer()
        let width : CGFloat = 2.0
        border.borderColor = UIColor.whiteColor().CGColor
        border.frame = CGRectMake(0, textField.frame.size.height-width, textField.frame.size.width, textField.frame.size.height)
        border.borderWidth = width
        textField.layer.addSublayer(border)
        textField.layer.masksToBounds = true
        let textFieldButton = UIBarButtonItem(customView: textField)
        
        //Search Button
        let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: nil)

        //Flexible Space
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        
        //Toolbar
        let toolbar = UIToolbar(frame: CGRectMake(0,20,view.frame.width,50))
        toolbar.sizeToFit()
        toolbar.barTintColor = UIColor.orangeColor()
        toolbar.translucent = false
        toolbar.tintColor = UIColor.whiteColor()
        toolbar.items = [fixed, text, fixed, textFieldButton, flexible, search]
        view.addSubview(toolbar)
    }
    
    func textFieldDidBeginEditing(textField: UITextField) {

        view.backgroundColor = UIColor.yellowColor()
        
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        view.backgroundColor = UIColor.cyanColor()
        
        //Hide the keyboard
        textField.resignFirstResponder()
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        
        view.backgroundColor = UIColor.whiteColor()

        //Hide the keyboard
        textField.resignFirstResponder()
        return true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:




Related information:

Adding UIBarButtonItem to UIToolbar with left/right alignment
UIBarButtonItem types and UIToolbar color settings

UIBarButtonItem types and UIToolbar color settings

This post shows the different UIBarButtonItem types in iOS as well as different UIToolbar color settings. The code is written in Swift 2.2 with Xcode 7.3.

Modify ViewController.swift as:


import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.yellowColor()
        
        let myColor = UIColor(red: 55.0/255.0, green: 210.0/255.0, blue: 200.0/255.0, alpha: 1.0)
        
        //Bar Button Items
        let action = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Action, target: self, action: nil)
        let add = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: nil)
        let bookmarks = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Bookmarks, target: self, action: nil)
        let camera = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Camera, target: self, action: nil)
        let cancel = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Cancel, target: self, action: nil)
        let compose = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Compose, target: self, action: nil)
        let done = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Done, target: self, action: nil)
        let edit = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Edit, target: self, action: nil)
        let fastForward = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: nil)
        let organize = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Organize, target: self, action: nil)
        let pause = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Pause, target: self, action: nil)
        let play = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Play, target: self, action: nil)
        let redo = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Redo, target: self, action: nil)
        let refresh = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Refresh, target: self, action: nil)
        let reply = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Reply, target: self, action: nil)
        let rewind = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Rewind, target: self, action: nil)
        let save = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Save, target: self, action: nil)
        let search = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Search, target: self, action: nil)
        let stop = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Stop, target: self, action: nil)
        let trash = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Trash, target: self, action: nil)
        let undo = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Undo, target: self, action: nil)
        let flexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: self, action: nil)
        
        //Bar Button Items in arrays
        let items1 = [action, flexible, add]
        let items2 = [bookmarks, flexible, camera]
        let items3 = [cancel, flexible, compose]
        let items4 = [done, flexible, edit]
        let items5 = [fastForward, flexible, organize]
        let items6 = [pause, flexible, play]
        let items7 = [redo, flexible, refresh]
        let items8 = [reply, flexible, rewind]
        let items9 = [save, flexible, search]
        let items10 = [stop, flexible, trash, flexible, undo]
        
        //Toolbar 1 - Background Color + No Translucent
        let toolbar1 = UIToolbar()
        toolbar1.sizeToFit()
        toolbar1.center = CGPointMake(view.frame.width/2, 50)
        toolbar1.backgroundColor = myColor
        toolbar1.translucent = false
        toolbar1.items = items1
        
        //Toolbar 2 - Background Color
        let toolbar2CenterY : CGFloat = toolbar1.center.y + toolbar1.frame.height
        let toolbar2 = UIToolbar()
        toolbar2.sizeToFit()
        toolbar2.center = CGPointMake(view.frame.width/2, toolbar2CenterY)
        toolbar2.backgroundColor = myColor
        toolbar2.items = items2
        
        //Toolbar 3 - Bar Tint Color
        let toolbar3CenterY : CGFloat = toolbar2.center.y + toolbar2.frame.height
        let toolbar3 = UIToolbar()
        toolbar3.sizeToFit()
        toolbar3.center = CGPointMake(view.frame.width/2, toolbar3CenterY)
        toolbar3.barTintColor = myColor
        toolbar3.items = items3
        
        //Toolbar 4 - Bar Tint Color + No Translucent
        let toolbar4CenterY : CGFloat = toolbar3.center.y + toolbar3.frame.height
        let toolbar4 = UIToolbar()
        toolbar4.sizeToFit()
        toolbar4.center = CGPointMake(view.frame.width/2, toolbar4CenterY)
        toolbar4.barTintColor = myColor
        toolbar4.translucent = false
        toolbar4.items = items4
        
        //Toolbar 5 - Bar Tint Color + No Translucent + White Tint Color
        let toolbar5CenterY : CGFloat = toolbar4.center.y + toolbar4.frame.height
        let toolbar5 = UIToolbar()
        toolbar5.sizeToFit()
        toolbar5.center = CGPointMake(view.frame.width/2, toolbar5CenterY)
        toolbar5.barTintColor = myColor
        toolbar5.translucent = false
        toolbar5.tintColor = UIColor.whiteColor()
        toolbar5.items = items5
        
        //Toolbar 6 - Background Color + No Translucent
        let toolbar6CenterY : CGFloat = toolbar5.center.y + toolbar5.frame.height+50
        let toolbar6 = UIToolbar()
        toolbar6.sizeToFit()
        toolbar6.center = CGPointMake(view.frame.width/2, toolbar6CenterY)
        toolbar6.backgroundColor = UIColor.orangeColor()
        toolbar6.translucent = false
        toolbar6.items = items6
        
        //Toolbar 7 - Background Color
        let toolbar7CenterY : CGFloat = toolbar6.center.y + toolbar6.frame.height
        let toolbar7 = UIToolbar()
        toolbar7.sizeToFit()
        toolbar7.center = CGPointMake(view.frame.width/2, toolbar7CenterY)
        toolbar7.backgroundColor = UIColor.orangeColor()
        toolbar7.items = items7
        
        //Toolbar 8 - Bar Tint Color
        let toolbar8CenterY : CGFloat = toolbar7.center.y + toolbar7.frame.height
        let toolbar8 = UIToolbar()
        toolbar8.sizeToFit()
        toolbar8.center = CGPointMake(view.frame.width/2, toolbar8CenterY)
        toolbar8.barTintColor = UIColor.orangeColor()
        toolbar8.items = items8
        
        //Toolbar 9 - Bar Tint Color + No Translucent
        let toolbar9CenterY : CGFloat = toolbar8.center.y + toolbar8.frame.height
        let toolbar9 = UIToolbar()
        toolbar9.sizeToFit()
        toolbar9.center = CGPointMake(view.frame.width/2, toolbar9CenterY)
        toolbar9.barTintColor = UIColor.orangeColor()
        toolbar9.translucent = false
        toolbar9.items = items9
        
        //Toolbar 10 - Bar Tint Color + No Translucent + White Tint Color
        let toolbar10CenterY : CGFloat = toolbar9.center.y + toolbar9.frame.height
        let toolbar10 = UIToolbar()
        toolbar10.sizeToFit()
        toolbar10.center = CGPointMake(view.frame.width/2, toolbar10CenterY)
        toolbar10.barTintColor = UIColor.orangeColor()
        toolbar10.translucent = false
        toolbar10.tintColor = UIColor.whiteColor()
        toolbar10.items = items10
        
        view.addSubview(toolbar1)
        view.addSubview(toolbar2)
        view.addSubview(toolbar3)
        view.addSubview(toolbar4)
        view.addSubview(toolbar5)
        view.addSubview(toolbar6)
        view.addSubview(toolbar7)
        view.addSubview(toolbar8)
        view.addSubview(toolbar9)
        view.addSubview(toolbar10)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:



Related Information:

Adding UIBarButtonItem to UIToolbar with left/right alignment