How to count number of contacts in swift? - ios

how to count number of contacts in swift
,i am very new to this ios platform i just wanted know how to access contact and count it. any valid inputs will be appreciated.
//
// ViewController.swift
// test1
//
// Created by Lakshmi Kanth N on 6/23/17.
// Copyright © 2017 Lakshmi Kanth N. All rights reserved.
//
import UIKit
import Contacts
import ContactsUI
import AddressBook
class ViewController: UIViewController, CNContactPickerDelegate{
#IBOutlet var label: UILabel!
#IBOutlet var click: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
// The container means
// that the source the contacts from, such as Exchange and iCloud
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
print (allContainers.count)
// 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.
}
#IBAction func obclick(_ sender: UIButton) {
let entieyType = CNEntityType.contacts
let authStatus = CNContactStore.authorizationStatus(for: entieyType)
if authStatus == CNAuthorizationStatus.notDetermined{
let contactStore = CNContactStore.init()
contactStore.requestAccess(for: entieyType, completionHandler: { (success, nil) in
if success {
self.openContacts()
}
else {
print("NOT")
}
})
}
else if authStatus == CNAuthorizationStatus.authorized{
self.openContacts()
}
}
func openContacts (){
let contactPicker = CNContactPickerViewController.init()
contactPicker.delegate = self
self.present(contactPicker, animated: true, completion: nil)
}
func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
picker.dismiss(animated: true) {
}
}
func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
}
}
above is my code which is used to access the contacts but i need to have a count of them

if item.isKeyAvailable(CNContactPhoneNumbersKey){
let phoneNOs=item.phoneNumbers
print("Phone No count \(phoneNOs.count)")
}

// You may add more "keys" to fetch referred to official documentation
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
// The container means
// that the source the contacts from, such as Exchange and iCloud
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
print (allContainers.count)
if u want to check for valid input for searching
var contacts: [CNContact] = []
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
do {
let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
// Put them into "contacts"
contacts.appendContentsOf(containerResults)
} catch {
print("Error fetching results for container")
}
}
print (containerResults.count)

Related

How to get the registered user Notification API data come for guest user too?

Current Scenario?:
Th registered user of the book app gets the notifications such as 'books available for download', q&A portal answers, live streaming link.
What is the goal?:
To get the notifications for guest where it can show the available books for download, and other notification that comes for registered user.
What is the issue/errors?:
When user clicks on the notification button , nothing comes on the screen. Everything blank and no notification is shown. It show the below error::
What i tried?:
When we call API, the token is generated from the backend. This token is then used to get the access. I tried to copy the API method to the home-screen that is used from 'signUpVC'(sign up view controller) to get the token bit showing above error.
Admin user notification looks as below:
Guest user (notification from our android app)
Code: for SignUp
import UIKit
import PKHUD
import SDWebImage
class SignupVC: ThemeController {
// MARK: - Outlets
#IBOutlet weak var imgProfile: TappableImageView!
#IBOutlet weak var passwordView: UIStackView!
#IBOutlet weak var lblRegister: UILabel!
var isFromUpdateProfile = Bool()
// -----------------------------------------------------------------------------------------------
// MARK: - Class Properties
#IBOutlet weak var txtFirstName: UITextField!
#IBOutlet weak var txtLastName: UITextField!
#IBOutlet weak var txtEmail: UITextField!
#IBOutlet weak var txtCity: UITextField!
#IBOutlet weak var txtPassword: UITextField!
// -----------------------------------------------------------------------------------------------
// MARK: - Memory Management Functions
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
deinit {
}
// -----------------------------------------------------------------------------------------------
// MARK: - Class Functions
private func errorsInTextFields() -> String? {
self.view.endEditing(true)
guard !txtFirstName.isEmpty else { return UserMessages.kBlankFirstName }
guard txtFirstName.hasValid(.alphabetWithSpace) else { return UserMessages.kValidFirstName }
guard !txtLastName.isEmpty else { return UserMessages.kBlankLastName }
guard txtLastName.hasValid(.alphabetWithSpace) else { return UserMessages.kValidLastName }
guard !txtEmail.isEmpty else { return UserMessages.kBlankEmail }
guard txtEmail.hasValid(.email) else { return UserMessages.kValidEmail }
guard !txtCity.isEmpty else { return UserMessages.kBlankCity }
guard txtCity.hasValid(.alphabetWithSpace) else { return UserMessages.kValidCity }
guard !txtPassword.isEmpty else { return UserMessages.kBlankPassword }
//guard txtPassword.hasValid(.password) else { return UserMessages.kValidPassword }
// No Errors
return nil
}
private func errorsInEditProfileTextFields() -> String? {
self.view.endEditing(true)
guard !txtFirstName.isEmpty else { return UserMessages.kBlankFirstName }
guard txtFirstName.hasValid(.alphabetWithSpace) else { return UserMessages.kValidFirstName }
guard !txtLastName.isEmpty else { return UserMessages.kBlankLastName }
guard txtLastName.hasValid(.alphabetWithSpace) else { return UserMessages.kValidLastName }
guard !txtEmail.isEmpty else { return UserMessages.kBlankEmail }
guard txtEmail.hasValid(.email) else { return UserMessages.kValidEmail }
guard !txtCity.isEmpty else { return UserMessages.kBlankCity }
guard txtCity.hasValid(.alphabetWithSpace) else { return UserMessages.kValidCity }
// No Errors
return nil
}
// -----------------------------------------------------------------------------------------------
// MARK: - Action Functions
#IBAction func btnRegisterAction(_ sender: RoundButton) {
if let _ = User.current?.accessToken{
//TextField Verification
if let error = errorsInEditProfileTextFields() {
SnackBar.show(error)
return
}
//API Calling
self.apiEditProfileCall()
}else{
//TextField Verification
if let error = errorsInTextFields() {
SnackBar.show(error)
return
}
//API Calling
apiRegisterDeviceCall()
}
}
// -----------------------------------------------------------------------------------------------
// MARK: - Web Service Functions
private func apiRegisterDeviceCall() {
HUD.show(.progress)
var deviceToken:String = UserDefaults.standard.string(forKey: "DeviceToken") ?? "empty"
let parameters: [String: Any] = [
"vDeviceUniqueId" : DeviceManager.deviceUniqueId,
"txDeviceToken" : deviceToken,
"tDeviceOs" : DeviceManager.deviceOS,
"vDeviceName" : DeviceManager.modelName,
"vResolution" : DeviceManager.resolution,
"vOsVersion" : DeviceManager.osVersion,
]
print(parameters)
APIManager.shared.makeRequest(method: .registerDevice, parameters: parameters, withLoader: false) { (response, error) in
print(response)
if let accessToken = response["data"]["access_token"].string {
UserDefaults.standard.setValue(accessToken, forKey: "AccessToken")
self.apiRegisterCall()
} else {
HUD.hide()
SnackBar.show("Something went wrong")
}
}
}
private func apiRegisterCall() {
let parameters: [String: Any] = [
"vFirstName" : txtFirstName.trimmedText,
"vLastName" : txtLastName.trimmedText,
"vEmail" : txtEmail.trimmedText,
"vPassword" : txtPassword.trimmedText,
"vCityName" : txtCity.trimmedText,
]
var images: [String: UIImage] = [:]
if let image = imgProfile.image {
images["txProfileImageUrl"] = image
}
APIManager.shared.makeRequest(method: .registerUser, parameters: parameters, imageParameters: images, withLoader: false) { (response, error) in
HUD.hide()
if response["data"].exists() {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
self.popViewController()
}
// Alert.showWith("User Registered", message: "Please check your email inbox for varification email", positiveTitle: "Ok", shouldResignOnTouchOutside: false) { isOk in
// if isOk {
// DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
// self.popViewController()
// }
// }
// }
} else {
SnackBar.show(response["message"].stringValue)
}
}
}
private func apiEditProfileCall() {
HUD.show(.progress)
let parameters: [String: Any] = [
"vFirstName" : txtFirstName.trimmedText,
"vLastName" : txtLastName.trimmedText,
"vEmail" : txtEmail.trimmedText,
"vCityName" : txtCity.trimmedText,
]
var images: [String: UIImage] = [:]
if let image = imgProfile.image {
images["txProfileImageUrl"] = image
}
APIManager.shared.makeRequest(method: .editProfile, parameters: parameters, imageParameters: images, withLoader: false) { (response, error) in
HUD.hide()
if response["data"].exists(){
if let accessToken = User.current?.accessToken{
var updateUser = User(withJSON: response["data"])
updateUser.accessToken = accessToken
User.current = updateUser
SnackBar.show("Profile successfully updated.")
self.navigationController?.popViewControllers(viewsToPop: 2)
}
}else{
SnackBar.show(response["message"].stringValue)
}
}
}
// -----------------------------------------------------------------------------------------------
// MARK: - Life Cycle Functions
override func viewDidLoad() {
super.viewDidLoad()
if let _ = User.current?.accessToken{
self.passwordView.isHidden = true
self.lblRegister.text = "Update"
self.title = "Edit Profile"
self.imgProfile.sd_imageIndicator = SDWebImageActivityIndicator.gray
self.imgProfile.sd_setImage(with: URL(string: User.current!.profileImage), placeholderImage: nil)
self.txtFirstName.text = User.current!.firstName
self.txtLastName.text = User.current!.lastName
self.txtEmail.text = User.current!.email
self.txtCity.text = User.current!.cityName
}
}
// -----------------------------------------------------------------------------------------------
}

Swift3 Alamofire SwiftyJSON get data outside founcion

I was trying to get swfityjson and almo to work in Xcode 8
like in the post in this page:
Showing JSON data on TableView using SwiftyJSON and Alamofire
But I can not get the data from the self.
This helped me a little, but I am stuck with the count. Someone please help me with this, beacuse I am new to swift and have spent the day trying to understand how to get the count of rows and the data out of the almo function.
import UIKit
import Alamofire
import SwiftyJSON
class TableViewController: UITableViewController {
var names = [String]()
var rowCount = [Int]()
var tableTitle = [String]()
typealias JSONStandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func callAlamo(){
let url = "http://xxxxxx/xxxx/xxxxxx.php"
//let id = UserDefaults.standard.string(forKey: "UserDefaults")
Alamofire.request(url).responseJSON{(respones)->Void in
if let value = respones.result.value{
let json = JSON(value)
let rows = json["items"].arrayValue
for anItem in rows {
let title: String? = anItem["SupplierName"].stringValue
self.tableTitle.append(title!)
//print(self.tableTitle.count)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
// let isUserLoggedin = UserDefaults.standard.boll(forKey: "userLogIn")
let ststus = UserDefaults.standard.string(forKey: "userLogIn")
if ststus == "false" {
self.performSegue(withIdentifier: "loginView", sender: self)
}else{
callAlamo()
}
}
#IBAction func logout(_ sender: AnyObject) {
UserDefaults.standard.set(false, forKey: "userLogIn")
UserDefaults.standard.synchronize()
self.performSegue(withIdentifier: "loginView", sender: self)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print (tableTitle)
return self.tableTitle.count
}
}
I am unable to get the tableTitle.count. Thanks!
UITableView Delegate methods are called before viewDidAppear. So you need to reload the UITableView after got the response from server
DispatchQueue.main.async {
self.tableView.reloadData()
}
After the for loop.
import UIKit
import Alamofire
import SwiftyJSON
class TableViewController: UITableViewController {
var names = [String]()
var rowCount = [Int]()
var tableTitle = [String]()
typealias JSONStandard = [String : AnyObject]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
func callAlamo(){
let url = "http://pos1.dermedia.co.il/iphone/getLasttransactions.php?cardid="
//let id = UserDefaults.standard.string(forKey: "UserDefaults")
Alamofire.request(url).responseJSON{(respones)->Void in
if let value = respones.result.value{
let json = JSON(value)
// print (json["items"].arrayValue)
let rows = json["items"].arrayValue
// print (rows)
for anItem in rows {
let title: String? = anItem["SupplierName"].stringValue
self.tableTitle.append(title!)
print(self.tableTitle.count)
}
}
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewDidAppear(_ animated: Bool) {
// let isUserLoggedin = UserDefaults.standard.boll(forKey: "userLogIn")
let ststus = UserDefaults.standard.string(forKey: "userLogIn")
if ststus == "false" {
self.performSegue(withIdentifier: "loginView", sender: self)
}else{
callAlamo()
print ("gggggg")
print(self.tableTitle.count)
}
}
#IBAction func logout(_ sender: AnyObject) {
UserDefaults.standard.set(false, forKey: "userLogIn")
UserDefaults.standard.synchronize()
self.performSegue(withIdentifier: "loginView", sender: self)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print (self.tableTitle)
print("hhh")
return tableTitle.count
}
}

Userdefaults to save switch state

I Have a switch that when turned to "on" will put the music and when the switch is set to "off" the music will resume playing. My problem is that when i leave the view controller the switch will appear as "off" when it is switch "on". The code for my switch is below, I'm not sure what to write in order for the app to remember the switch state, please help.
//
// SecondViewController.swift
// Urban Sphere
//
// Created by Oren Edrich on 9/11/16.
// Copyright © 2016 Oren Edrich. All rights reserved.
//
import Foundation
import UIKit
import SpriteKit
import AVFoundation
var bombSoundEffect: AVAudioPlayer!
var Ghost = SKSpriteNode()
class SecondViewController: UIViewController {
var sw = false
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed(_ sender: AnyObject) {
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
}
I found the correct answer and decided to post it incase anyone has the same question.
#IBAction func saveSwitchState(sender: AnyObject) {
var defaults = NSUserDefaults.standardUserDefaults()
if bluetoothSwitch.on {
defaults.setBool(true, forKey: "SwitchState")
} else {
defaults.setBool(false, forKey: "SwitchState")
}
}
and...
override func viewDidLoad() {
super.viewDidLoad()
var defaults = NSUserDefaults.standardUserDefaults()
if (defaults.objectForKey("SwitchState") != nil) {
bluetoothSwitch.on = defaults.boolForKey("SwitchState")
}
}
You want know where to insert the code , I guess.
updata
updata2
Then you can run directly. If it's useful , please UP this answer.
import Foundation
import UIKit
import SpriteKit
import AVFoundation
class SecondViewController: UIViewController {
static let bombSoundEffect = {()->(AVAudioPlayer) in
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
return try! AVAudioPlayer(contentsOf: url)
}()
var sw = false
var Ghost = SKSpriteNode()
#IBOutlet var mySwitch: UISwitch!
#IBAction func switchpressed() {
if mySwitch.isOn{
SecondViewController.bombSoundEffect.play()
}else{
SecondViewController.bombSoundEffect.stop()
}
//************* save status *************
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
}
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.addTarget(self, action: #selector(switchpressed), for: .valueChanged)
//************* load status *************
mySwitch.isOn = UserDefaults.standard.bool(forKey: "SwitchStatus");
switchpressed()
}
}
I have a similar situation to yours, and I just use UserDefaults. Here's a step-by-step guide on how to do it.
Create a variable like the following example. This will set the default setting and store the state of the check box for use later:
var musicSetting = UserDefaults().string(forKey: "Music") ?? "On"
In your viewDidLoad, add an if statement that will check whether the Check Box should be On or Off, like this:
if musicSetting == "On" {
theNameOfYourSwitch.isOn = false
} else {
theNameOfYourSwitch.isOn = true
}
In the IBAction property for your check box, add an if statement like the following that will save your Setting, depending on what it is:
if theNameOfYourCheckbox.state == NSOnState {
UserDefaults().set("On", forKey: "Music")
} else {
UserDefaults().set("Off", forKey: "Music")
}
Here's a screenshot that might help:
If you want to save the state of Switch in user default, then can use the
native method
UserDefaults.standard.set(_ value: Bool, forKey defaultName: String)
Like this
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
UserDefaults.standard.synchronize();
While fetching switch status just use
let status = UserDefaults.standard.bool(forKey: "SwitchStatus");
UPDATE :
#IBAction func switchpressed(_ sender: AnyObject) {
UserDefaults.standard.set(mySwitch.isOn, forKey: "SwitchStatus");
if mySwitch.isOn{
if bombSoundEffect != nil {
bombSoundEffect.stop()
bombSoundEffect = nil
}
}
else{
let path = Bundle.main.path(forResource: "newmusic.wav", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
bombSoundEffect = sound
sound.numberOfLoops = -1
sound.play()
} catch {
// couldn't load file :(
}
}
}
Hope it helps
Happy coding ...

pass data with Button in swift

I try to pass data from my ViewController to TableViewPlace.swiftUse the buttons. When I am choosing button return not some thing
viViewController
class ViewController: UIViewController {
struct Country{
var id :Int
init(id:Int){
self.id = id
}
}
var CountrySelected = [Country]()
var countryArry = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
// 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.
}
#IBAction func airAction(sender: AnyObject) {
}
#IBAction func viewPlaceAction(sender: AnyObject) {
getParsePlaceView()
// json viewPlace
performSegueWithIdentifier("viewPlaceSegu", sender: sender)
}
#IBAction func tourAction(sender: AnyObject) {
}
/// Open the page
// parse json
func getParsePlaceView(){
let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
NSURLSession.sharedSession().dataTaskWithURL(url!){ [unowned self] (data , repsonse , error) in
if error != nil {
print(error!)
} else {
do {
let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
for post in posts {
if let id = post["userId"] as? Int{
// print(id)
let sets = Country(id: id)
self.CountrySelected.append(sets)
}
}
self.countryArry = posts
print(self.countryArry)// return data and currect
} catch let error as NSError {
print(error)
}
}
}.resume()
print(countryArry) // return nil why??
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// get a reference to the second view controller
if segue.identifier == "viewPlaceSegu" {
if let secondViewController = segue.destinationViewController as? TableViewPlace {
// set a variable in the second view controller with the String to pass
print(countryArry)
secondViewController.tnt = countryArry
}
}
}
}
when I print(countryArry) return nil why ??
Can someone help me or give me a better solution?
You are creating a Post object with this line :
let countryPlace = Post(userid: post["userId"] as! Int, title: post["title"] as! String)
And you are trying to pass to your tableview this Post object to your tnt variable which is a ViewController class, this is why you've got the first error :
secondViewController.tnt = Country
Then, if you want to add your string country to your mutable array you have to do :
if let title = tnt.title {
Country.append(title)
}

I'm trying to get data from Parse and display it as a UILabel but I'm not getting any results

When I run this code it does not update the alertLabel to the message I have set on parse. Iim not getting any errors, and the label is correctly linked to my ViewController class.
I'm very new to coding so I would appreciate you help. Thanks in advance.
class ViewController: UIViewController {
#IBOutlet weak var alertLabel: UILabel!
var output : PFObject!
let theObjectID = "M0qEFWMxYI"
let theClass = "bobcatStatus"
override func viewDidLoad() {
super.viewDidLoad()
}
func displayData() {
var thisQuery = PFQuery(className: theClass)
thisQuery.getObjectWithId(theObjectID)
if let alertOutput = output["alertMessage"] as? String {
alertLabel.text = alertOutput
}
else {
alertLabel.text = "Error loading data."
}
}
// 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.
}
Xcode 6.2.3
#brianprsly i am assuming you are trying to get a record from parse class using object id, try to implement below code in your project. Let me know if it helps you.
Ref : https://www.parse.com/docs/ios/guide#objects-retrieving-objects
var query = PFQuery(className: theClass)
query.getObjectInBackgroundWithId(theObjectID) {
(theClassObj: PFObject?, error: NSError?) -> Void in
if error == nil && theClassObj != nil {
println(theClassObj)
if let alertOutput = theClassObj["alertMessage"] as? String {
alertLabel.text = alertOutput
}else {
alertLabel.text = "Error loading data."
}
} else {
println(error)
}
}

Resources