Showing posts with label image. Show all posts
Showing posts with label image. Show all posts

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()
    }

}

Wednesday, March 16, 2016

Google Sign-In for iOS - Display User Email and Profile Picture

Update April 27, 2016:
Step 3 - ViewController.swift is modified with Xcode 7.3 (Swift 2.2).

This post shows how to display the user email and profile picture with Google Sign-In for iOS.

Procedure

1. Create a basic sign-in button with instructions in this tutorial:

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

2. Modify AppDelegate.swift:

//Modify signIn function with didSignInForUser:

    func signIn(signIn: GIDSignIn!, didSignInForUser user: GIDGoogleUser!,
        withError error: NSError!) {
            if (error == nil) {

                let name = user.profile.name
                let email = user.profile.email
                var imageURL = ""
                if user.profile.hasImage {
                    imageURL = user.profile.imageURLWithDimension(100).absoluteString
                }
                NSNotificationCenter.defaultCenter().postNotificationName(
                    "ToggleAuthUINotification",
                    object: nil,
                    userInfo: ["statusText": "Signed in user:\n\(name)""email" : email, "imageURL" : imageURL])

            }
...

//Modify signIn function with didDisconnectWithUser:

    func signIn(signIn: GIDSignIn!, didDisconnectWithUser user:GIDGoogleUser!,
        withError error: NSError!) {
            NSNotificationCenter.defaultCenter().postNotificationName(
                "ToggleAuthUINotification",
                object: nil,
                userInfo: ["statusText": "User has disconnected.", "email" : ""])

    }

3. Modify ViewController.swift:


Update April 27, 2016:

import UIKit

class ViewController: UIViewController, GIDSignInUIDelegate {

    var btnSignIn : GIDSignInButton!
    var btnSignOut : UIButton!
    var btnDisconnect : UIButton!
    var label : UILabel!
    
    var imageView : UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        GIDSignIn.sharedInstance().uiDelegate = self
        
        btnSignIn = GIDSignInButton(frame: CGRectMake(0,0,230,48))
        btnSignIn.center = view.center
        btnSignIn.style = GIDSignInButtonStyle.Standard
        view.addSubview(btnSignIn)
        
        btnSignOut = UIButton(frame: CGRectMake(0,0,100,30))
        btnSignOut.center = CGPointMake(view.center.x, 100)
        btnSignOut.setTitle("Sign Out", forState: UIControlState.Normal)
        btnSignOut.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        btnSignOut.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        btnSignOut.addTarget(self, action: #selector(btnSignOutPressed), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(btnSignOut)
        
        btnDisconnect = UIButton(frame: CGRectMake(0,0,100,30))
        btnDisconnect.center = CGPointMake(view.center.x, 200)
        btnDisconnect.setTitle("Disconnect", forState: UIControlState.Normal)
        btnDisconnect.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
        btnDisconnect.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
        btnDisconnect.addTarget(self, action: #selector(btnDisconnectPressed), forControlEvents: UIControlEvents.TouchUpInside)
        view.addSubview(btnDisconnect)
        
        label = UILabel(frame: CGRectMake(0,0,300,200))
        label.center = CGPointMake(view.center.x, 430)
        label.numberOfLines = 0
        label.text = "Please Sign in."
        label.textAlignment = NSTextAlignment.Center
        view.addSubview(label)
        
        imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
        imageView.center = view.center
        view.addSubview(imageView)
        
        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: #selector(receiveToggleAuthUINotification(_:)),
            name: "ToggleAuthUINotification",
            object: nil)
        
        toggleAuthUI()
    }
    
    func btnSignOutPressed() {
        print(GIDSignIn.sharedInstance().currentUser.profile.email)
        print(GIDSignIn.sharedInstance().currentUser.profile.name)
        
        GIDSignIn.sharedInstance().disconnect()
        label.text = "Disconnecting."
    }
    
    func btnDisconnectPressed() {
        label.text = "Signed out."
        toggleAuthUI()
    }
    
    func toggleAuthUI() {
        print("toggleAuthUI")
        if (GIDSignIn.sharedInstance().hasAuthInKeychain()){

            // Signed in
            btnSignIn.hidden = true
            btnSignOut.hidden = false
            btnDisconnect.hidden = false
            
            //NEW!! The code below is required if the app is restarted and already signed in previously.
            if (GIDSignIn.sharedInstance().currentUser == nil) {
                print("no user info")
                GIDSignIn.sharedInstance().signInSilently()
            }
        } else {
            btnSignIn.hidden = false
            btnSignOut.hidden = true
            btnDisconnect.hidden = true
        }
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self,
            name: "ToggleAuthUINotification",
            object: nil)
    }
    
    @objc func receiveToggleAuthUINotification(notification: NSNotification) {
        if (notification.name == "ToggleAuthUINotification") {
            self.toggleAuthUI()
            if notification.userInfo != nil {
                let userInfo:Dictionary<String,String!> =
                notification.userInfo as! Dictionary<String,String!>
                self.label.text = userInfo["statusText"]!+"\n\(userInfo["email"]!)"
                if userInfo["imageURL"] == nil {
                    self.imageView.image = nil
                } else {
                    let url = NSURL(string: userInfo["imageURL"]!)!
                    self.imageView.image = UIImage(data: NSData(contentsOfURL: url)!)
                }
            }
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

=====
Original post March 16, 2016:

//Modified blue texts:


    var imageView : UIImageView!
    
    override func viewDidLoad() {

        ...

        label = UILabel(frame: CGRectMake(0,0,300,200))
        label.center = CGPointMake(view.center.x, 430)
        label.numberOfLines = 0
        label.text = "Please Sign in."
        label.textAlignment = NSTextAlignment.Center
        view.addSubview(label)
        
        imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
        imageView.center = view.center
        view.addSubview(imageView)

        ...

//And modify this:


    @objc func receiveToggleAuthUINotification(notification: NSNotification) {
        if (notification.name == "ToggleAuthUINotification") {
            self.toggleAuthUI()
            if notification.userInfo != nil {
                let userInfo:Dictionary<String,String!> =
                notification.userInfo as! Dictionary<String,String!>
                self.label.text = userInfo["statusText"]!+"\n\(userInfo["email"]!)"
                if userInfo["imageURL"] == nil {
                    self.imageView.image = nil
                } else {
                    let url = NSURL(string: userInfo["imageURL"]!)!
                    self.imageView.image = UIImage(data: NSData(contentsOfURL: url)!)
                }
            }
        }

    }
=====

Result

Related Information:

Google Sign-In for iOS - Create a GIDSignInButton programmatically in Swift
Google Sign-In for iOS - Get User Name, Email and Profile Picture without Nofitication
Google Sign-In for iOS - Create a custom sign-in button programmatically
Facebook SDK and Swift - Display User Name and Profile Picture

Thursday, January 14, 2016

Facebook SDK and Swift - Display User Name and Profile Picture

Update (November 10, 2016) - Swift 3.0.1 (Xcode 8.1)
This post shows how to display the Facebook user name and profile image on a simple iOS app using Swift 2.1.1 (Xcode 7.2).

1. Download a facebook icon from facebookbrand.com.

2. Include the FBSDK frameworks into an Xcode project and modify AppDelegate.swift:

See this tutorial: Facebook SDK and Swift - Create a Facebook Login Button

3. Drag the fb-art.jpg file into the Xcode project.

4. Modify ViewController.swift as:

Update (November 10, 2016) - Swift 3.0.1 (Xcode 8.1) 

import UIKit
import FBSDKLoginKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate {
    
    var imageView : UIImageView!
    var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        imageView.center = CGPoint(x: view.center.x, y: 200)
        imageView.image = UIImage(named: "fb-art.jpg")
        view.addSubview(imageView)
        
        label = UILabel(frame: CGRect(x: 0, y: 0, width: 200, height: 30))
        label.center = CGPoint(x: view.center.x, y: 300)
        label.text = "Not Logged In"
        label.textAlignment = NSTextAlignment.center
        view.addSubview(label)
        
        let loginButton = FBSDKLoginButton()
        loginButton.center = CGPoint(x: view.center.x, y: 400)
        loginButton.delegate = self
        view.addSubview(loginButton)
        
        getFacebookUserInfo()
    }
    
    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("loginButtonDidLogOut")
        imageView.image = UIImage(named: "fb-art.jpg")
        label.text = "Not Logged In"
    }
    
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        print("didCompleteWith")
        getFacebookUserInfo()
    }
    
    func getFacebookUserInfo() {
        if(FBSDKAccessToken.current() != nil)
        {
            //print permissions, such as public_profile
            print(FBSDKAccessToken.current().permissions)
            let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, name, email"])
            let connection = FBSDKGraphRequestConnection()

            connection.add(graphRequest, completionHandler: { (connection, result, error) -> Void in
                
                let data = result as! [String : AnyObject]
                
                self.label.text = data["name"] as? String
                
                let FBid = data["id"] as? String
                
                let url = NSURL(string: "https://graph.facebook.com/\(FBid!)/picture?type=large&return_ssl_resources=1")
                self.imageView.image = UIImage(data: NSData(contentsOf: url! as URL)! as Data)
            })
            connection.start()
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Original post (January 14, 2016) - Swift 2.1.1 (Xcode 7.2) 


import UIKit
import FBSDKLoginKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate {
    
    var imageView : UIImageView!
    var label: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        imageView = UIImageView(frame: CGRectMake(0, 0, 100, 100))
        imageView.center = CGPoint(x: view.center.x, y: 200)
        imageView.image = UIImage(named: "fb-art.jpg")
        view.addSubview(imageView)
        
        label = UILabel(frame: CGRectMake(0,0,200,30))
        label.center = CGPoint(x: view.center.x, y: 300)
        label.text = "Not Logged In"
        label.textAlignment = NSTextAlignment.Center
        view.addSubview(label)
        
        let loginButton = FBSDKLoginButton()
        loginButton.center = CGPoint(x: view.center.x, y: 400)
        loginButton.delegate = self
        view.addSubview(loginButton)
        
        getFacebookUserInfo()
    }
    
    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        print("didCompleteWithResult")
        
        getFacebookUserInfo()
    }
    
    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
        print("loginButtonDidLogOut")
        imageView.image = UIImage(named: "fb-art.jpg")
        label.text = "Not Logged In"
    }
    
    func getFacebookUserInfo() {
        if(FBSDKAccessToken.currentAccessToken() != nil)
        {
            //print permissions, such as public_profile
            print(FBSDKAccessToken.currentAccessToken().permissions)
            let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, name, email"])
            graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
                
                self.label.text = result.valueForKey("name") as? String
                
                let FBid = result.valueForKey("id") as? String
                
                let url = NSURL(string: "https://graph.facebook.com/\(FBid!)/picture?type=large&return_ssl_resources=1")
                self.imageView.image = UIImage(data: NSData(contentsOfURL: url!)!)
            })
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

Result:

When the app is started:



After logged in:
Related Information:
Facebook SDK for iOS - Getting Started
Facebook SDK and Swift - Get Facebook SDK Version
Facebook SDK for iOS Changelog (SDK Version History)
Facebook Login Review Guide (App review by Facebook is required in some conditions.)
Facebook SDK and Swift - Post a message and an image to Facebook
Facebook SDK and Swift - Post a message using Graph API and post an image using FBSDKShareKit
Facebook SDK and Swift - Create a custom login button programmatically

Google Sign-In for iOS - Display User Email and Profile Picture