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.
Xcode 8
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 🙂
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 🙂
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.
How to use Alamofire and SwiftyJSON with Swift? – Swift 3 – iOS 10 – Xcode 8
Alamofire is an HTTP networking library written in Swift.
SwiftyJSON makes it easy to deal with JSON data in Swift.
How to work with IBDesignable and IBInspectable in Swift Language?
How to use the @IBDesignable and @IBInspectable?
By giving you a simple example that we can not change the corner radius from the design view. We have to change it run time. If you want to make possible it with design time then you can use the @IBDesignable and @IBInspectable.
So, We are taking an example as IBButtonExtender for this the functionality
- Border Color
- Border Width
- Corner Radius
Create an Custom Class for UIButton with @IBDesignable
1 2 3 |
@IBDesignable class ButtonExtender: UIButton { } |
Create an @IBInspectable for Inspect the element. the Border Color property will be added to the list in the right panel when you create button with this class.
1 2 3 4 5 |
@IBInspectable var borderColor: UIColor = UIColor.white { didSet { layer.borderColor = borderColor.cgColor } } |
Set Initialization functions and other @IBInspectable as above.
You can check the code for the ButtonExtender.swift
IBButtonExtender
Presenting the ButtonExtender for Border Color, Border Width and Corner Radius function with the @IBDesignable and @IBInspectable in the Swift Language.
By making some corner radius and colors, You will get neat and clean output.
Github
Find IBButtonExtender on github 🙂
Check other articles on Swift Language.
All suggestions are acceptable. Put it in the comments!
Happy Coding 🙂
Facebook Login – Swift Language – iOS 10 – Swift 3
Facebook Login using custom button in Swift Language
Xcode Version 8
Article is Updated with the Facebook 4.16 SDK [27-September-2016].
Install Pods
1 2 3 4 5 6 7 8 |
platform :ios, '9.0' target 'FBSwiftLogin' do use_frameworks! # Pods for FBSwiftLogin pod 'FacebookCore' pod 'FacebookLogin' pod 'FacebookShare' end |
Appdelegate.swift
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import UIKit import FBSDKLoginKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) } func applicationWillResignActive(_ application: UIApplication) { FBSDKAppEvents.activateApp() } func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool { return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation) } } |
ViewController.swift
Create touch up inside event for custom button like as follows
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
// // ViewController.swift // FBSwiftLogin // // Created by Ashish Kakkad on 05/10/16. // Copyright © 2016 Kode. All rights reserved. // import UIKit import FBSDKLoginKit class ViewController: UIViewController { var dict : [String : AnyObject]! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func btnFBLoginPressed(_ sender: AnyObject) { let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager() fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in if (error == nil){ let fbloginresult : FBSDKLoginManagerLoginResult = result! if fbloginresult.grantedPermissions != nil { if(fbloginresult.grantedPermissions.contains("email")) { self.getFBUserData() fbLoginManager.logOut() } } } } } func getFBUserData(){ if((FBSDKAccessToken.current()) != nil){ FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in if (error == nil){ self.dict = result as! [String : AnyObject] print(result!) print(self.dict) } }) } } } |
In iOS 10 don’t forget to set capabilities (Keychain Sharing) :
Go to your project targets -> Capabilities -> Keychain Sharing -> Toggle Switch ON
Detailed Output Log :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{ email = "ashishkakkad8@gmail.com"; "first_name" = Ashish; id = 1227390383984537; "last_name" = Kakkad; name = "Ashish Kakkad"; picture = { data = { "is_silhouette" = 0; url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/14192077_1193042490752660_7942165287960590731_n.jpg?oh=bf3bedc4f98190a8f588fc8c3f911328&oe=58ABC3CC&__gda__=1486868896_cfe22abf7b2d6559f3609d8c51fc0663"; }; }; } |
Happy Coding 😀
Update : JSON Array Parsing in Swift Language – Swift 3 – iOS 10 – Xcode 8
So, how to parse following type of JSON?
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 26 |
"contacts": [ { "id": "c200", "name": "Ashish Kakkad", "email": "ashishhkakkad@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } }, { "id": "c201", "name": "Johnny Depp", "email": "johnny_depp@gmail.com", "address": "xx-xx-xxxx,x - street, x - country", "gender" : "male", "phone": { "mobile": "+91 0000000000", "home": "00 000000", "office": "00 000000" } } ] |
Create JSON Array Object :
1 2 3 4 5 6 7 8 9 |
let url=URL(string:"https://ashishkakkad.com/contacts.json") do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] if let arrJSON = allContacts["contacts"] { } } catch { } |
Parse JSON Array Object :
1 2 3 4 5 6 7 8 9 |
if let arrJSON = allContacts["contacts"] { for index in 0...arrJSON.count-1 { let aObject = arrJSON[index] as! [String : AnyObject] names.append(aObject["name"] as! String) contacts.append(aObject["email"] as! String) } } print(names) print(contacts) |
Complete code snippet with UITableView:
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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// // ViewController.swift // SwiftJSONParsingDemo // // Created by Ashish Kakkad on 12/10/16. // Copyright © 2016 Kode. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var names: [String] = [] var contacts: [String] = [] override func viewDidLoad() { super.viewDidLoad() let url=URL(string:"https://ashishkakkad.com/contacts.json") do { let allContactsData = try Data(contentsOf: url!) let allContacts = try JSONSerialization.jsonObject(with: allContactsData, options: JSONSerialization.ReadingOptions.allowFragments) as! [String : AnyObject] if let arrJSON = allContacts["contacts"] { for index in 0...arrJSON.count-1 { let aObject = arrJSON[index] as! [String : AnyObject] names.append(aObject["name"] as! String) contacts.append(aObject["email"] as! String) } } print(names) print(contacts) self.tableView.reloadData() } catch { } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return self.names.count; } func tableView(_ tableView: UITableView!, didSelectRowAtIndexPath indexPath: IndexPath!) { print("You selected name : "+names[indexPath.row]) } func tableView(_ tableView: UITableView, cellForRowAtIndexPath indexPath: IndexPath) -> UITableViewCell{ var cell = tableView.dequeueReusableCell(withIdentifier: "cell") if !(cell != nil) { cell = UITableViewCell(style: .subtitle, reuseIdentifier: "cell") } cell?.textLabel?.text=self.names[indexPath.row] cell?.detailTextLabel?.text = self.contacts[indexPath.row] return cell! } } |
Posted a gist on github.
Helping, Learning, Coding 🙂
XML Parsing in Swift Language – iOS 10 – XMLParser
Code syntax is changed in version Swift 3. So, I have updated this article with Xcode 8 – iOS 10
Here is tutorial about how to parse the XML data in Swift Language – iOS 10 – XMLParser
Start with creating object of XMLParser
[code language=”obj-c”]
var parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self
[/code]
Delegate your class with XMLParserDelegate
[code language=”obj-c”]
class ViewController: UIViewController,XMLParserDelegate {
}
[/code]
Add Delegate methods
[code language=”obj-c”]
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
}
[/code]
Parse the XML with following method
[code language=”obj-c”]
parser.parse()
[/code]
Complete sample code:
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController,XMLParserDelegate {
var strXMLData:String = ""
var currentElement:String = ""
var passData:Bool=false
var passName:Bool=false
var parser = XMLParser()
@IBOutlet var lblNameData : UILabel! = nil
override func viewDidLoad() {
super.viewDidLoad()
let url:String="http://api.androidhive.info/pizza/?format=xml"
let urlToSend: URL = URL(string: url)!
// Parse the XML
parser = XMLParser(contentsOf: urlToSend)!
parser.delegate = self
let success:Bool = parser.parse()
if success {
print("parse success!")
print(strXMLData)
lblNameData.text=strXMLData
} else {
print("parse failure!")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
currentElement=elementName;
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=true;
}
passData=true;
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
currentElement="";
if(elementName=="id" || elementName=="name" || elementName=="cost" || elementName=="description")
{
if(elementName=="name"){
passName=false;
}
passData=false;
}
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if(passName){
strXMLData=strXMLData+"\n\n"+string
}
if(passData)
{
print(string)
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("failure error: ", parseError)
}
}
[/code]
Code Demo on My Github. Both Swift 2.2 and Swift 3 versions are available.
Helping, Learning, Coding 🙂