Here is simple steps to requesting access to the Address Book in Swift Language iOS 8
Import the framework of Address Book:
[code language=”objc”]
import AddressBook
[/code]
Create an object of Address Book:
[code language=”objc”]
var addressBook: ABAddressBookRef?
[/code]
Create a method for assigning the value to addressBook:
[code language=”objc”]
func createAddressBook(){
var error: Unmanaged<CFError>?
addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
}
[/code]
Post following code to requesting access:
[code language=”objc”]
switch ABAddressBookGetAuthorizationStatus(){
case .Authorized:
println("Already authorized")
createAddressBook()
/* Access the address book */
case .Denied:
println("Denied access to address book")
case .NotDetermined:
createAddressBook()
if let theBook: ABAddressBookRef = addressBook{
ABAddressBookRequestAccessWithCompletion(theBook,
{(granted: Bool, error: CFError!) in
if granted{
println("Access granted")
} else {
println("Access not granted")
}
})
}
case .Restricted:
println("Access restricted")
default:
println("Other Problem")
}
[/code]
Happy Coding 🙂
Swift
How to add an Objective-C file in your Swift Project? or How to set Objective-C bridging header?
To import a set of Objective-C files in the same app target as your Swift code, you rely on an Objective-C bridging header to expose those files to Swift. Xcode offers to create this header file when you add an Objective-C file to an existing Swift app.
If you accept, Xcode creates the header file along with the file you were creating, and names it by your product module name followed by adding “-Bridging-Header.h”.
Alternatively, you can create a bridging header yourself by choosing File > New > File > (iOS or OS X) > Source > Header File.
You’ll need to edit the bridging header file to expose your Objective-C code to your Swift code.
To import Objective-C code into Swift from the same target
- In your Objective-C bridging header file, import every Objective-C header you want to expose to Swift.
For example:
[code language=”obj-c”]
#import "XYZCustomCell.h"
#import "XYZCustomView.h"
#import "XYZCustomViewController.h"
[/code] - Under Build Settings, make sure the Objective-C Bridging Header build setting under Swift Compiler – Code Generation has a path to the header.
The path should be relative to your project, similar to the way your Info.plist path is specified in Build Settings. In most cases, you should not need to modify this setting.
Any public Objective-C headers listed in this bridging header file will be visible to Swift. The Objective-C functionality will be available in any Swift file within that target automatically, without any import statements. Use your custom Objective-C code with the same Swift syntax you use with system classes.
For Example:
[code language=”obj-c”]
let myCell = XYZCustomCell()
myCell.subtitle = "A custom cell"
[/code]
Helping, Learning, Coding 🙂
Source : Apple Documents
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 🙂
Add Launch Screen (LaunchImage) for iPhone 6 | 6 Plus in Xcode 6 | iOS 8
Hello Developers,
Greetings for iPhone 6, 6 Plus and Xcode 6 GM Seed !!
Question is how to add launch screens for iPhone 6 and 6 Plus.
As per Apple’s Guidelines create the launch screens :
For iPhone 6: 750 x 1334 Pixels Resolution
For iPhone 6 Plus: 1242 x 2208 Pixels Resolution
You have two options :
- Create launch screen by LaunchScreen.xib.
- Add Launch Images in assets folder.
Finally set the Launch Screen Settings :
Happy Screening 😉
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 🙂
JSON Parsing in Swift Language – iOS 8
Here is tutorial about parsing JSON in Swift Language iOS 8
Create a Dictionary of all JSON data:
[code language=”obj-c”]
let url=NSURL(string:"http://api.androidhive.info/contacts/")
let allContactsData=NSData(contentsOfURL:url)
var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
NSLog("%@", allContacts)
[/code]
Parse the JSON by finding your key:
[code language=”obj-c”]
let contacts : AnyObject? = allContacts["contacts"]
for contacts in allContacts.keys {
println("All = \(contacts)")
let contact : AnyObject? = allContacts[contacts]
let collection = contact! as Array<Dictionary<String, AnyObject>>
for subContact in collection {
let name : AnyObject? = subContact["name"]
let email : AnyObject? = subContact["email"]
names+=name! as String
emails+=email! as String
println("Name: \(name)")
println("Email: \(email)")
}
}
[/code]
Complete code snippet with UITableView:
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
@IBOutlet var tblJson : UITableView = nil
var names: String[] = []
var emails: String[] = []
override func viewDidLoad() {
super.viewDidLoad()
let url=NSURL(string:"http://api.androidhive.info/contacts/")
let allContactsData=NSData(contentsOfURL:url)
var allContacts:Dictionary<String, AnyObject>=NSJSONSerialization.JSONObjectWithData(allContactsData, options: NSJSONReadingOptions.MutableContainers, error: nil) as Dictionary<String, AnyObject>
NSLog("%@", allContacts)
let contacts : AnyObject? = allContacts["contacts"]
for contacts in allContacts.keys {
println("All = \(contacts)")
let contact : AnyObject? = allContacts[contacts]
let collection = contact! as Array<Dictionary<String, AnyObject>>
for subContact in collection {
let name : AnyObject? = subContact["name"]
let email : AnyObject? = subContact["email"]
names+=name! as String
emails+=email! as String
println("Name: \(name)")
println("Email: \(email)")
}
}
println(names)
println(emails)
}
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!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as? UITableViewCell
if !cell {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
}
cell!.textLabel.text = self.names[indexPath.row]
cell!.detailTextLabel.text = self.emails[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected name : "+names[indexPath.row])
}
}
[/code]
Helping, Learning, Coding 🙂
Create Simple Table (UITableView) in Swift Language iOS8
Here is simple tutorial to create table (UITableView) in Swift Language – iOS 8 – Xcode 6
Attach your UITableView IBOutlet to .swift file
[code language=”obj-c”]
@IBOutlet var tblSwift : UITableView = nil
[/code]
Delegate UITableViewDelegate and UITableViewDataSource to your Controller
[code language=”obj-c”]
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
…
}
[/code]
Don’t forgot to add the delegate methods otherwise you got error
[code language=”obj-c”]
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
…
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
…
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
…
}
}
[/code]
Register your cell
[code language=”obj-c”]
override func viewDidLoad() {
super.viewDidLoad()
self.tblSwift.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}
[/code]
Following is sample of complete code
[code language=”obj-c”]
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource
{
@IBOutlet var tblSwift : UITableView = nil
var items: String[] = ["This", "is" , "swift" , "language" , ":)"]
override func viewDidLoad() {
super.viewDidLoad()
self.tblSwift.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return self.items.count;
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
var cell:UITableViewCell = self.tblSwift.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
cell.textLabel.text = self.items[indexPath.row]
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
println("You selected item "+items[indexPath.row]) //or
println("You selected item \(items[indexPath.row])") //or
println("You selected cell #\(indexPath.row)!")
}
}
[/code]
Helping, Learning, Coding 🙂
Working with Alert in Swift Language – iOS 8 – Xcode 6
In iOS 8 the UIAlertView is deprecated. Now UIAlertController is a single class for creating and interacting with what we knew as UIAlertView.
We have to create alert as follows.
[code language=”obj-c”]
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
[/code]
We can also create handler for handle the events on alert.
[code language=”obj-c”]
var alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
switch action.style{
case .Default:
println("default")
break
case .Cancel:
println("cancel")
break
case .Destructive:
println("destructive")
break
}
}))
self.presentViewController(alert, animated: true, completion: nil)
[/code]
Happy Coding 🙂
For more iOS tutorials visit iTuts.
Create a application in Xcode 6 – iOS 8 without storyborard in Swift language and work with controls
We can create navigation-based application without storyboard in Xcode 6 (iOS 8) like as follows:
- Create an empty application by selecting the project language as Swift.
- Add new cocoa touch class files with the interface xib. (eg. TestViewController)
- In the swift we have only one file interact with the xib i.e. *.swift file, there is no .h and .m files.
- We can connect the controls of xib with swift file same as in iOS 7.
Following are some snippets for work with the controls and Swift !
[code lang=”obj-c”]
//
// TestViewController.swift
//
import UIKit
class TestViewController: UIViewController {
@IBOutlet var testBtn : UIButton
init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
// Custom initialization
}
@IBAction func testActionOnBtn(sender : UIButton) {
let cancelButtonTitle = NSLocalizedString("OK", comment: "")
let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
// Create the action.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("The simple alert’s cancel action occured.")
}
// Add the action.
alertController.addAction(cancelAction)
presentViewController(alertController, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
[/code]
Changes in AppDelegate.swift file
[code lang=”obj-c”]
//
// AppDelegate.swift
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var navigationController: UINavigationController?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
self.window!.backgroundColor = UIColor.whiteColor()
self.window!.makeKeyAndVisible()
var testController: TestViewController? = TestViewController(nibName: "TestViewController", bundle: nil)
self.navigationController = UINavigationController(rootViewController: testController)
self.window!.rootViewController = self.navigationController
return true
}
func applicationWillResignActive(application: UIApplication) {
}
func applicationDidEnterBackground(application: UIApplication) {
}
func applicationWillEnterForeground(application: UIApplication) {
}
func applicationDidBecomeActive(application: UIApplication) {
}
func applicationWillTerminate(application: UIApplication) {
}
}
[/code]
Happy Coding 🙂