Firebase Authentication gives us backend services to authenticate users with your app. It provides SDKs and ready-made UI libraries. It supports authentication using passwords, and other providers like Google, Facebook and Twitter, Github, and more.
Swift Language
Firebase Remote Config [Swift]
Firebase Remote Config is used to change the application behavior without publishing update of application.
Basic setup is to create project at firebase console.
I am adding a video here to setup the firebase remote config.
Add core firebase to your project
Follow the steps available at : Add Firebase to your iOS Project
Steps to add remote config to your app
- Installation
Update your project with required cocoapods
123456789# Uncomment the next line to define a global platform for your projectplatform :ios, '9.0'target 'FireSwiftRemoteConfig' do# Comment the next line if you're not using Swift and don't want to use dynamic frameworksuse_frameworks!# Pods for FireSwiftRemoteConfigpod 'Firebase/Core'pod 'Firebase/RemoteConfig'end
Run pod install from terminal and open the created .xcworkspace file. - Configure Firebase Module
Just import firebase module and apply configure method. It will configure by itself by using GoogleService-Info.plist.
1234567891011import UIKitimport Firebase@UIApplicationMainclass AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {// Firebase ConfigurationFIRApp.configure()return true}} - Configure remote config
Create Remote Config object, as shown in the following example:
12345var remoteConfig: FIRRemoteConfig!override func viewDidLoad() {super.viewDidLoad()remoteConfig = FIRRemoteConfig.remoteConfig()}
Create an plist file for default values of configuration and set it to remote config:
123let remoteConfigSettings = FIRRemoteConfigSettings(developerModeEnabled: true)remoteConfig.configSettings = remoteConfigSettings!remoteConfig.setDefaultsFromPlistFileName("FireSwiftRemoteConfigDefaults")
FireSwiftRemoteConfigDefaults.plist with sampleURL key:
12345678<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><dict><key>sampleURL</key><string>http://google.com</string></dict></plist>
Use current default key from your defaults set on plist file and send fetch request in remote config to get the configuration keys set on the firebase console:
1234567891011121314151617func fetchConfiguration() {lblResult.text = remoteConfig[sampleURLConfigKey].stringValuevar expirationDuration = 3600if remoteConfig.configSettings.isDeveloperModeEnabled {expirationDuration = 0}remoteConfig.fetch(withExpirationDuration: TimeInterval(expirationDuration)) { (status, error) -> Void inif status == .success {print("Config fetched!")self.remoteConfig.activateFetched()} else {print("Config not fetched")print("Error \(error!.localizedDescription)")}lblResult.text = remoteConfig[sampleURLConfigKey].stringValue}}
Note : If in developer mode cacheExpiration is set to 0 so each fetch will retrieve values from the server. The default expiration duration is 43200 (12 hours).
All Done.
Sample code available at Github. There are many other things with firebase, I will try give update in next tutorials.
If you like then Buy me a coffee ☕️
Happy Coding 🙂
Refined API Naming : Migrating to Swift 3!
Xcode 8.0 comes with a Swift Migrator tool that helps you migrate your project to Swift 3, or update it to work with Swift 2.3 and the new SDKs.
Push Notifications in iOS 10 [Swift]
The new framework called “UserNotifications” is introduced with iOS 10 SDK. The UserNotifications framework (UserNotifications.framework) supports the delivery and handling of local and remote notifications.
So, Let see what we have to change to get the push notifications in iOS 10.
Steps to use Legacy Swift in Xcode 8
Xcode 8.0 is released with Swift 3 and Swift 2.3 compatibility.
If you already having a project with Swift 2.2 language support with Xcode 7.3.1 and you open the project in Xcode 8.0 then, you will be prompted for the migration assistant to do a migration pass. The assistant can also be invoked manually from the menu Edit -> Convert -> To Current Swift Syntax…
- Use Swift 2.3 Modifies your project to enable the Use Legacy Swift build setting and provides source changes to be able to build against the new SDKs.
- Use Swift 3 This is recommended. You will get source changes to be able to build your project using Swift 3 and take advantage of all the new features in Xcode 8.0.
If you want to work with new project and you want to work with Legacy code (Swift 2.3) or 3.0 then you can do settings from build settings as follows :
Default Setting is No (Swift 3). But if you want to do legacy code (Swift 2.3) then you have to select Yes (Swift 2.3).
Make sure you do this setting by starting of new project because many methods will change.
For Example :
Swift 3 Code
[code language=”obj-c”]
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
[/code]
Swift 2.3 Code
[code language=”obj-c”]
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
return true
}
[/code]
As per my opinion Swift 3 is recommended.
Happy Coding 🙂
Bye Bye to NS from Swift!!
Many of the types are bridged to the Swift type like as (e.g., NSString being bridged to String).
Other Objective-C types are bridged to Swift are as follows :
Objective-C | Swift |
---|---|
NSString | String |
NSArray | Array |
NSDictionary | Dictionary |
NSData | Data |
NSError | Error (Added Swift 3 – Xcode 8 Beta 4) |
NSNotificationCenter | NotificationCenter |
And more…
Bye Bye to NS from Swift!!
Happy Coding 🙂
Best Tweets of iOS 10 & Swift 3 Updates
Use a struct instead of a string as your dictionary key for better performance ? #swiftlang #WWDC16 pic.twitter.com/9ITOLwyHox
— NatashaTheRobot (@NatashaTheRobot) June 19, 2016
So excited about the Swift Performance session already!#WWDC16 #swiftlang pic.twitter.com/vJAjrAJJjN
— NatashaTheRobot (@NatashaTheRobot) June 19, 2016
You can now know when the user dismisses your notification ? #WWDC16 #iOS10 #iosdev
— NatashaTheRobot (@NatashaTheRobot) June 19, 2016
Media Attachments in Notifications ?? #WWDC16 #iOS10 #iosdev pic.twitter.com/o7EopfE9wg
— NatashaTheRobot (@NatashaTheRobot) June 19, 2016
Whoa! We can now access the users notification settings for our app ??? #WWDC16 #iOS10 #iosdev pic.twitter.com/8fo9faLA6T
— NatashaTheRobot (@NatashaTheRobot) June 19, 2016
Oooh #keyPath in Swift 3.0 ? #byebyestrings pic.twitter.com/E9mj9NH7al
— Ayaka Nonaka (@ayanonagon) June 18, 2016
Now that I’ve had some time to recover from WWDC, I highlighted some of my favorite ? 3.0 features. Hope you enjoy! https://t.co/hm77J2NZV3
— Ayaka Nonaka (@ayanonagon) June 19, 2016
replacement for the graphics context creation pic.twitter.com/687sZCsxoD
— Alejandro Martinez (@alexito4) June 19, 2016
Before and after of Core Graphics (old C API) in Swift thanks to compiler magic using NS_SWIFT_NAME in Swift 3.0! ? pic.twitter.com/uJYANo5wqU
— Ayaka Nonaka (@ayanonagon) June 18, 2016
Get Reactions from Timeline Post via Facebook Graph API – Swift – iOS
New version of SDK is 4.16.x(Swift) and Graph API Version is 2.8.
With the Graph API 2.6 Facebook has given support to fetch (read only) the Reactions on Timeline Posts.
Post is updated for iOS 10 and Swift 3
API documentation is available here.
Let’s learn how to get reactions from the post
Install pods
1 2 3 4 5 6 7 8 9 |
# Uncomment the next line to define a global platform for your project platform :ios, '9.0' target 'FBSwiftLogin' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! # Pods for FBSwiftLogin pod 'FacebookCore' pod 'FacebookLogin' end |
Login with Facebook
I have already written a tutorial on Facebook Login.
Get Facebook Posts via Graph API
We can get the Facebook post via graph API : /me/posts for that we have to add user_posts permission with login.
1 2 3 4 5 6 7 |
func getFacebookUserPosts() { FBSDKGraphRequest(graphPath: "/me/posts", parameters: nil, httpMethod: "GET").start(completionHandler: { (connection, result, error) in if (error == nil){ print(result) } }) } |
Get Reactions from one of the Post
We can get the Facebook post reactions via graph API : /{post-id}/reactions. We have to pass parameters like fields and summary as described in getReactions function.
Note : Here I am writing sample for only first post.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
func getFacebookUserPosts() { var strGraphPath : String = "" FBSDKGraphRequest(graphPath: "/me/posts", parameters: nil, httpMethod: "GET").start(completionHandler: { (connection, result, error) in if (error == nil){ print(result) let data = (result as! [String : Any])["data"] as! [[String : Any]] if(data.count > 0) { let strId = data[0]["id"] as! String strGraphPath = "/"+strId+"/reactions" self.getReactions(strGraphPath) } } }) } func getReactions(_ strGraphPath:String) { FBSDKGraphRequest(graphPath: strGraphPath, parameters: ["fields":"id, name, type", "summary":"total_count, viewer_reaction"], httpMethod: "GET").start(completionHandler: { (connection, result, error) in if (error == nil){ print(result) } }) } |
Response should be like
Type of reactions : NONE, LIKE, LOVE, WOW, HAHA, SAD, ANGRY
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
{ data = ( { id = ACCOUNT_ID; name = "NAME"; type = HAHA; }, { id = ACCOUNT_ID; name = "NAME"; type = LIKE; } ); paging = { cursors = { after = REFERENCE_ID; before = REFERENCE_ID; }; next = "NEXT_REFERENCE_LINK"; }; summary = { "total_count" = 56; "viewer_reaction" = NONE; }; } |
#Like #Share #React 🙂 😛 😀
Happy coding 🙂
Use of Operator Overloading with Swift
I was just going through the Swift document and I found that Swift allow to overload the operator just like as C++ Language. Objective-C doesn’t allow to overload the operator.
As swift document we can also say “Operator Functions”.
Let’s Overload ^ (XOR Operator) to make Power of the value
Function Prototype :
Declare function prototype with left hand side value and right and side value.
1 2 |
func ^(lhs: Int, rhs: Int) -> Int { } |
Operations in the function :
To make the power of the value we have to apply following operations
1 2 3 4 5 6 7 8 9 10 11 12 |
func ^(lhs: Int, rhs: Int) -> Int { if(rhs == 0) { return 1 } else { var result = lhs for _ in 1 ..< rhs { result *= lhs } return result } } |
Let’s try to use with the operator :
1 2 3 |
let a = 2^2 //4 let b = 2^4 //16 let c = 3^3 //27 |
Happy Coding 🙂
Swift 2.2 Warnings and It's Solutions – Xcode 7.3
Xcode 7.3 came with Swift 2.2 Version. I just updated to Xcode 7.3 and found following warnings because of Swift version change.
List of warnings with it’s solution:
- ‘var’ parameters are deprecated and will be removed in Swift 3
- Use of string literal for Objective-C selectors is deprecated; use ‘#selector’ instead
- ‘++’ is deprecated: it will be removed in Swift 3
- C-style for statement is deprecated and will be removed in a future version of Swift
- __FILE__ is deprecated and will be removed in Swift 3, please use #file
Warning with:
[code language=”obj-c”]
func functionTest(var param:String) {
print(param)
}
[/code]
Solution:
[code language=”obj-c”]
func functionTest(param:String) {
print(param)
}
[/code]
If you want to update that variable inside the function then you have to create copy of that variable to do operations on that.
Warning with:
[code language=”obj-c”]
btn.addTarget(self, action: "functionName", forControlEvents: UIControlEvents.TouchUpInside)
[/code]
OR
[code language=”obj-c”]
btn.addTarget(self, action: Selector("functionName"), forControlEvents: UIControlEvents.TouchUpInside)
[/code]
Solution:
[code language=”obj-c”]
btn.addTarget(self, action: #selector(ViewController.functionName), forControlEvents: UIControlEvents.TouchUpInside)
[/code]
Apple Documentation : Added information about the #selector syntax for Objective-C selectors to the Selector Expression section.
Warning with:
[code language=”obj-c”]
var i = 0
for str in arrStr {
print(str)
i++
}
[/code]
Solution:
[code language=”obj-c”]
var i = 0
for str in arrStr {
print(str)
i += 1
}
[/code]
Apple Documentation : Removed discussion of C-style for loops, the ++ prefix and postfix operators, and the — prefix and postfix operators.
Warning with:
[code language=”obj-c”]
for var i=0; i<arrStr.count; i += 1 {
print(arrStr[i])
}
[/code]
Solution:
[code language=”obj-c”]
for i in 0 ..< arrStr.count {
print(arrStr[i])
}
[/code]
Warning with:
[code language=”obj-c”]
__FILE__
[/code]
Solution:
[code language=”obj-c”]
#file
[/code]
More swift tutorials/articles are available here.
Happy Coding 🙂