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.
iTuts
SwiftGoingFaster by Precompiled Bridging Headers
Faster Mix-and-Match Builds with Precompiled Bridging Headers
PROBLEM :
Every time a Swift file in a mixed-language target is compiled, the Swift compiler parses the project’s bridging header in order to make Objective-C code visible to Swift code. When the bridging header is large and the Swift compiler runs many times – as in a debug configuration – the cost of repeatedly parsing the bridging header can be a substantial part of the overall build time.
In Swift 3.1, you can reduced debug build time by 30% by using the new -enable-bridging-pch Swift flag for this issue. This mode is still experimental and must be manually enabled, but it will be enabled by default if developer feedback indicates it’s working well and providing significant speedup… so try it out!
Related Link : Faster Mix-and-Match Builds with Precompiled Bridging Headers
Happy Coding 🙂
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 🙂
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.
Push Notifications in iOS 10 [Objective-C]
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 for implement code to handle push notifications in iOS 10
Import UserNotifications.framework in your AppDelegate file
1 |
#import <UserNotifications/UserNotifications.h> |
Also add UNUserNotificationCenterDelegate.
1 2 3 4 |
#import <UserNotifications/UserNotifications.h> @interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate> @end |
Register for push notification
Before registration check the version of iOS and then based on versions do the code. For iOS 7 code was different, fro iOS 8 & 9 code was different and again for iOS 10 code is different.
As per my opinion you have to set the deployment target to iOS 8 or iOS 9 and later. For this you can check the adoption ratio of iOS in the devices.
Define constant for version check :
1 |
#define SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending) |
Add code in your did finish launching
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ [self registerForRemoteNotifications]; return YES; } - (void)registerForRemoteNotifications { if(SYSTEM_VERSION_GRATERTHAN_OR_EQUALTO(@"10.0")){ UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; center.delegate = self; [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error){ if(!error){ [[UIApplication sharedApplication] registerForRemoteNotifications]; } }]; } else { // Code for old versions } } |
Handling delegate methods for UserNotifications
You will be surprise that notification displayed when application in foreground too in iOS 10. As we know that in old versions we display alert or something else which will be look like notification comes in foreground.
There are two delegate methods need to be handled :
1 2 3 4 5 6 7 8 9 10 11 |
//Called when a notification is delivered to a foreground app. -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler{ NSLog(@"User Info : %@",notification.request.content.userInfo); completionHandler(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge); } //Called to let your app know which action was selected by the user for a given notification. -(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)())completionHandler{ NSLog(@"User Info : %@",response.notification.request.content.userInfo); completionHandler(); } |
Add Push Notifications Entitlements
Go to your project target’s Capabilities tab and add Push Notifications Entitlements.
If it’s available in your certificates then it will enable directly else configure your profile with the certificates and you can enable this capability by that.
All Done!
Happy Coding ?
I have added sample code of objective-c on github with iOS 8, 9 and 10 support of push notification.
I have also posted about Push Notifications in iOS 10 [Swift].
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 🙂
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 🙂
How to create a wrapper for Alamofire and SwiftyJSON? Swift – iOS
This blogpost updated with Swift 3 – Xcode 8 – iOS 10 – Alamofire 4.0
I have posted a basic tutorial about Alamofire and SwiftyJSON How to use Alamofire and SwiftyJSON with Swift?
And some day before we have learned about Use of Blocks(Closures) or Completion Handlers with Function in Swift – iOS
Let’s combine both the topics to make a WRAPPER of Alamofire and SwiftyJSON.
Use of Blocks(Closures) or Completion Handlers with Function in Swift – iOS
Blocks in Objective-C
In Objective-C we are using the blocks(completion handlers) with functions as follows :
[code language=”obj-c”]
– (void)yourFunctionName:(NSString *)yourString withCompletionHandler:(void (^)(NSString *yourResult))block;
[/code]
Closures in Swift
Closures are self-contained blocks of functionality that can be passed around and used in your code. Closures in Swift are similar to blocks in C and Objective-C and to lambdas in other programming languages.
Syntax with Function
[code language=”obj-c”]
func yourFunctionName(parameter:Type, … , withCompletionHandler:(result:Type) -> Void)
[/code]
For more closure syntax : goshdarnclosuresyntax.com
Example
Function Definition:
[code language=”obj-c”]
func closureReturn(isTest:Bool, withCompletionHandler:(result:String) -> Void) {
if(isTest){
withCompletionHandler(result: "Yes")
}
else{
withCompletionHandler(result: "No")
}
}
[/code]
Calling Function:
[code language=”obj-c”]
closureReturn(true) { (result) -> Void in
print(result)
}
[/code]
Output should be respective to value true/false.
In next post I will write a tutorial on a wrapper class for Alamofire with use of SwiftyJSON by using closures.
It will be related to this post How to use Alamofire and SwiftyJSON with Swift? – Swift 2 – iOS 9 – Xcode 7
Happy Coding 🙂