Tutorial: How To Share in Facebook SDK 4.1.x for Swift
There are a couple of ways to integrate Facebook Sharing into your app. The first and easiest is using the existing Social Framework that is embedded in iOS. If you want to go this route, read my article about it here: Tutorial: Share on Twitter and Facebook in Swift.
The other option is to use the native Facebook SDK. This will require that a user is logged into Facebook using Facebook Login. In this tutorial we’ll cover how to integrate Facebook Share into your app using the native Facebook 4.0 SDK using Swift.
You can share three different types of content using Facebook, they are Links, Photos & Videos. Let’s cover each of them.
To begin, follow the steps in this article to integrate the Facebook SDK and implement Facebook Login: Tutorial: How To Use Login in Facebook SDK 4.0 for Swift.
Import the Share Kit Framework
- Add the FacebookSDKShareKit.Framework & Bolts.framework to your project just like your did with the FacebookSDKCoreKit.Framework. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
- Add the following import statement to your Bridging-Header.h, right below the Core Kit entry.
#import
- Add the Facebook Share buttons to your ViewController.swift.
Share a Link on Facebook
When people share links from your app to Facebook, it includes attributes that show up in the post:
contentURL – the link to be shared
contentTitle – represents the title of the content in the link
imageURL – the URL of thumbnail image that appears on the post
contentDescription – of the content, usually 2-4 sentences
Here’s the code to show and execute the Link button:
let content : FBSDKShareLinkContent = FBSDKShareLinkContent() content.contentURL = NSURL(string: "") content.contentTitle = " " content.contentDescription = " " content.imageURL = NSURL(string: " ") let button : FBSDKShareButton = FBSDKShareButton() button.shareContent = content button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25) self.view.addSubview(button)
Share a Photo on Facebook
People can share photos from your app to Facebook with the Share Dialog or with a custom interface:
- Photos must be less than 12MB in size
- People need the native Facebook for iOS app installed, version 7.0 or higher
Build your share content for photos with the FBSDKSharePhotoContent model.
Note: You will not be able to test this in the Simulator, you’ll need to test on your device.
Here’s the code to show and execute the Photo button from an image picker:
First you’ll need to add the UIImagePickerControllerDelgate and UINavigationController Delegate to your class definition.
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
Then add the code to display a button on the screen for the User to select a photo:
let button : UIButton = UIButton() button.backgroundColor = UIColor.blueColor() button.setTitle("Choose Photo", forState: .Normal) button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 125, 150, 25) button.addTarget(self, action: "photoBtnClicked", forControlEvents: .TouchUpInside) self.view.addSubview(button) let label : UILabel = UILabel() label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 100, 200, 25) label.text = "Photos Example" label.textAlignment = .Center self.view.addSubview(label)
When the User clicks the button, the following method is called to show the iOS image picker:
func photoBtnClicked(){ if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){ println("Photo capture") imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum; imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } }
Once the User selects a photo, the following delegate method is called.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let photo : FBSDKSharePhoto = FBSDKSharePhoto() photo.image = info[UIImagePickerControllerOriginalImage] as! UIImage photo.userGenerated = true let content : FBSDKSharePhotoContent = FBSDKSharePhotoContent() content.photos = [photo] }
Share a Video on Facebook
People using your app can share videos to Facebook with the Share dialog or with your own custom interface:
- Videos must be less than 12MB in size
- People who share should have Facebook for iOS client installed, version 26.0 or higher.
Build your share content for photos with the FBSDKShareVideoContent model.
Note: You will not be able to test this in the Simulator, you’ll need to test on your device.
Here’s the code to show and execute the Video button from an image picker:
First you’ll need to add the UIImagePickerControllerDelgate and UINavigationController Delegate to your class definition.
class ViewController: UIViewController, FBSDKLoginButtonDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate
Then add the code to display a button on the screen for the User to select a video:
let button : UIButton = UIButton() button.backgroundColor = UIColor.blueColor() button.setTitle("Choose Video", forState: .Normal) button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 150) * 0.5, 200, 150, 25) button.addTarget(self, action: "videoBtnClicked", forControlEvents: .TouchUpInside) self.view.addSubview(button) let label : UILabel = UILabel() label.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 200) * 0.5, 175, 200, 25) label.text = "Video Example" label.textAlignment = .Center self.view.addSubview(label)
When the User clicks the button, the following method is called to show the iOS video picker:
func videoBtnClicked(){ if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.SavedPhotosAlbum){ println("Video capture") imagePicker.delegate = self imagePicker.sourceType = UIImagePickerControllerSourceType.SavedPhotosAlbum imagePicker.allowsEditing = false self.presentViewController(imagePicker, animated: true, completion: nil) } }
Once the User selects a video, the following delegate method is called.
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) { let video : FBSDKShareVideo = FBSDKShareVideo() video.videoURL = info[UIImagePickerControllerMediaURL] as! NSURL let content : FBSDKShareVideoContent = FBSDKShareVideoContent() content.video = video }
You can grab the full source code for this tutorial. Note: Created using XCode 6.3 (Swift 1.2).
If you need it built using Xcode 6.2 (Swift 1.1).
Tutorial: How To Use Login in Facebook SDK 4.1.x for Swift
It’s been a long time but Facebook has finally released a new version of their SDK. It’s not built using Swift, I guess that still makes it compatible with Objective-C. In this tutorial we’ll go through the steps to install the SDK and implement Facebook Login using the SDK in Swift.
Get your Application Setup with the Facebook SDK
- Visit the Getting Started with the Facebook iOS SDK documentation to download the Facebook SDK and install it.
- Add the FacebookSDKCoreKit.Framework to your project as you normally would. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
- You won’t be able to use the normal #import <FBSDKCoreKit/FBSDKCoreKit.h> to link the framework so you need to do a work around by creating a Bridging Header.
- Create a new “Objective-C” Header file by clicking “File > New”
- All you need in the Bridging-Header.h is the import statement for the Facebook SDK.
// // Bridging-Header.h // FacebookTutorial // // Created by Brian Coleman on 2015-03-27. // Copyright (c) 2015 Brian Coleman. All rights reserved. // #ifndef FacebookTutorial_Bridging_Header_h #define FacebookTutorial_Bridging_Header_h #import
#endif - Add it to your target’s build settings:In Xcode, if you go into the build settings for your target, and scroll all the way down you’ll find a “Swift Compiler – Code Generation” section.
Set “Objective-C Bridging Header” to <#PROJECT_NAME>/Bridging-Header.h
“Install Objective-C Compatibility Header”, should be set to “Yes”.
- Now your app should be able to access all of the APIs in the Facebook SDK.
- Add the following to your AppDelegate.swift. The “OpenURL” method allows your app to open again after the user has validated their login credentials.
- The FBSDKAppEvents.activateApp() method allows Facebook to capture events within your application including Ads clicked on from Facebook to track downloads from Facebook and events like how many times your app was opened.
// // AppDelegate.swift // FacebookTutorial // // Created by Brian Coleman on 2015-03-27. // Copyright (c) 2015 Brian Coleman. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application( application, openURL: url, sourceApplication: sourceApplication, annotation: annotation) } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. FBSDKAppEvents.activateApp() } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
Facebook Login for iOS
Now we’ll setup our app to use Facebook Login.
- Add the FacebookSDKLoginKit.Framework & Bolts.framework to your project just like your did with the FacebookSDKCoreKit.Framework. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
- Add the following import statement to your Bridging-Header.h, right below the Core Kit entry.
#import
- Add the Facebook Login button to your ViewController.swift.
- After you add the button, you should update your view controller to check for an existing token at load. This eliminates an unnecessary app switch to Facebook if someone already granted permissions to your app.
- When you add Facebook Login, your app can ask someone for permissions on a subset of that person’s data. Use the readPermissions or publishPermissions property of the FBSDKLoginButton.
// // ViewController.swift // FacebookTutorial // // Created by Brian Coleman on 2015-03-27. // Copyright (c) 2015 Brian Coleman. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. if (FBSDKAccessToken.currentAccessToken() != nil) { // User is already logged in, do work such as go to next view controller. } else { let loginView : FBSDKLoginButton = FBSDKLoginButton() self.view.addSubview(loginView) loginView.center = self.view.center loginView.readPermissions = ["public_profile", "email", "user_friends"] loginView.delegate = self } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
Using the FBSDKLoginButtonDelegate Methods
- Add in the additional code for the FBSDKLoginButtonDelegate. This is helpful to know if the user did login correctly and if they did you can grab their information.
- First add the delegate FBSDKLoginButtonDelegate to the class definition.
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
- Add the following callback methods to your View Controller.
// Facebook Delegate Methods func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) { println("User Logged In") if ((error) != nil) { // Process error } else if result.isCancelled { // Handle cancellations } else { // If you ask for multiple permissions at once, you // should check if specific permissions missing if result.grantedPermissions.contains("email") { // Do work } } } func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) { println("User Logged Out") }
- Here is an extra method to grab the Users Facebook data. You can call this method anytime after a user has logged in by calling self.returnUserData().
func returnUserData() { let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil) graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error println("Error: \(error)") } else { println("fetched user: \(result)") let userName : NSString = result.valueForKey("name") as! NSString println("User Name is: \(userName)") let userEmail : NSString = result.valueForKey("email") as! NSString println("User Email is: \(userEmail)") } }) }
Enter your Facebook App Information
- There is one final step needed to be performed, and that is to add three new keys to the project’s .plist file. So, open it by clicking on the Supporting Files group in the Project Navigator and then on the Info.plist file. Add a new key named FacebookAppID, and as its value paste the App ID value which you can copy from the Facebook dashboard, at the top of it. Similarly, add the FacebookDisplayName key, and in its value paste the Display Name.Finally, create a new key named URL Types, and set its type to array with one item only. Give it the URL Schemes title and make it an array too. In the one and only item that should be contained, set the app ID value you copied from the Facebook dashboard, prefixing it with the fb literal. The image below shows all the three additions on the .plist file:
- Compile your project and you should see the following screen. Once you click the “Log in with Facebook” button, it should kick you out to the Facebook App or the Facebook website for the user to login. After they have, it’ll kick back to your app and you’ll see the user information in the console.
Now it’s up to you to use the users information as you wish. Maybe to populate a user profile or to pull the users Facebook friends so you can build a leaderboard.
You can grab the full source code for this tutorial. Note: Created using XCode 6.3 (Swift 1.2).
If you need it built using Xcode 6.2 (Swift 1.1).
Tutorial: Check for Internet Connection in Swift
There are many reasons you need to check if the user is connected to the internet within your app, most important is that your app needs to retrieve data from a feed or display a web view. As soon as your app is loaded and before you make any calls to get data from a feed you should check if the user is connected to the internet.
In the past in Objective-C the most common way to check for connectivity is using Reachability, but it hasn’t been converted to Swift as of yet. Below is a simple way to add this feature to your new Swift project.
- Create a new Swift file within your project, name it “Reachability.swift”.
- Cut & paste the following code into it to create your class.
import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { return false } let isReachable = flags == .Reachable let needsConnection = flags == .ConnectionRequired return isReachable && !needsConnection } }
- You can check internet connection anywhere in your project using this code:
if Reachability.isConnectedToNetwork() == true { println("Internet connection OK") } else { println("Internet connection FAILED") }
- If the user is not connected to the internet, you may want to show them an alert dialog to notify them.
if Reachability.isConnectedToNetwork() == true { println("Internet connection OK") } else { println("Internet connection FAILED") var alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK") alert.show() }
You can grab the full source code for this tutorial. Note: Built for Xcode 7.1.
Tutorial: Play Video in Swift
Recently I needed to add a video as a background in one of my apps. This is a really nice effect if it’s a looping video. On top of the video I had some other elements and buttons, it was cool to see motion happening behind. The code snippet below displays the video full screen with no controls and it repeats, but you could change the properties to suit your needs.
- First add the video to your project, just like any file, you can drag it into your Project Navigator or right click in the Project Navigator and select “Add Files”. Be sure to choose the targets that you need to add the file to, if you have more than one.
- In the Project Navigator select your Project Root > Your Target > Build Phases > Copy Bundle Resources. Check to see that you video is there, if not click the plus sign to add it.
- Add this import statement to the top of your View Controller.
import MediaPlayer
- Add this property to your class.
var moviePlayer : MPMoviePlayerController!
- Add the code below to create and play your video. This can be added to your ViewDidLoad() method or create your own function.
let path = NSBundle.mainBundle().pathForResource("Video", ofType:"mp4") let url = NSURL.fileURLWithPath(path!) self.moviePlayer = MPMoviePlayerController(contentURL: url) if let player = self.moviePlayer { player.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height) player.view.sizeToFit() player.scalingMode = MPMovieScalingMode.Fill player.fullscreen = true player.controlStyle = MPMovieControlStyle.None player.movieSourceType = MPMovieSourceType.File player.repeatMode = MPMovieRepeatMode.One player.play() self.view.addSubview(player.view) }
Get Started with Apple Watch and WatchKit
It’s finally here, we’ve been waiting a long time since we heard the rumours of an iWatch, and now with the release of Xcode 6.2 and the iOS 8.2 SDK Apple has included WatchKit so we can begin developing for it at last. What kind of watch app are you going to make?
Let’s look at the three kinds of watch interfaces you can include in your app.
WatchKit Apps
A Watch app is the basis for interacting with your content on Apple Watch. Watch apps are accessible from the home screen and usually provide only a portion of the functionality of their containing iOS app. The purpose of a Watch app is to give the user quick but more in-depth access to app-related data.
The Watch app works in tandem with a corresponding WatchKit extension running on the user’s iPhone. The Watch app contains no custom code and is used only to store the storyboards and resource files associated with your user interface. The WatchKit extension is the brains of the operation. It contains the business logic and code you use to manage your content, respond to user interactions, and update your user interface. And because it runs on the user’s iPhone, the WatchKit extension can easily coordinate with your iOS app to gather location updates or perform other long-running tasks.
Learn how to make a Watch App, Tutorial: Building an Apple Watch App
Glances
A glance is a focused interface for presenting important information that the user needs right now. Glances are aptly named because they are intended to be looked at quickly by the user. Glances do not scroll, so the entire glance interface must fit on a single screen. Glances are read-only and cannot contain buttons, switches, or other interactive controls. Tapping a glance launches your Watch app.
The code for managing a glance resides in your WatchKit extension. The classes you use to manage your glance interface are the same ones you use for your Watch app. Even though the classes and basic behaviour are the same, a glance is simpler to implement because it does not respond to user interactions.
Learn how to make a Glance, Tutorial: Building an Apple Watch Glance
Actionable Notifications
Apple Watch works with its paired iPhone to display local and remote notifications. Initially, Apple Watch uses a minimal interface to display incoming notifications. When the user’s movement indicates a desire to see more information, the minimal interface changes to a more detailed interface displaying the contents of the notification. Apps can provide their own customized version of this detailed interface and add custom graphics or arrange the notification data differently than the default interface provided by the system.
Apple Watch supports the interactive notifications that were introduced in iOS 8. Interactive notifications are a way to add buttons to a notification that reflect immediate actions the user can take. For example, an incoming calendar event might include buttons to accept or reject a meeting invitation. When your iOS app registers support for interactive notifications, Apple Watch automatically adds appropriate buttons to both the custom and default notification interfaces. All you need to do is handle the actions selected by the user in your WatchKit extension.
Learn how to make a Dynamic Notification, Tutorial: Building an Apple Watch Notification
Getting Started with WatchKit video
Apple has made a great video to help us understand the architecture, the APIs available and how the interface works.
Development Resources
- Apple Watch Human Interface Guidelines
- Xcode 6.2 beta, including iOS 8.2 SDK with WatchKit
- iOS 8.2 beta in iOS Dev Center
- WatchKit Programming Guide
- WatchKit Framework Reference
- WatchKit Catalog: Using WatchKit Interface Elements
- Lister: A Productivity App (Obj-C and Swift)
- WatchKit Catalog: Using WatchKit Interface Elements