Access Users Contacts Phone Numbers CNContacts - ios

I am trying to get to phone numbers of my contacts using CNContact, i want to have the number as a simple string of its didgits such as "04xxxxxxxx" but the closest I can get to is the following. ("contact" is of type CNContact)
contact.phoneNumbers[0].value
\\Which prints: <CNPhoneNumber: 0x13560a550: countryCode=au, digits=04xxxxxxxx>
ive tried all the obvious things and not so obvious things, thanks

If anyone has a more legitimate solution please do post it, otherwise this rather hacky approach works:
let value = String(contact.phoneNumbers[0].value)
let start = value.rangeOfString("digits=")!.endIndex
let end = value.endIndex.predecessor()
let number = value.substringWithRange(Range<String.Index>(start: start, end: end))

Using this category you can now access the phone number via swift.
don't forget to include this file in the bridging header
#implementation CNPhoneNumber (SwiftSupport)
- (NSString*)toString {
return self.stringValue;
}
#end

Fetch the number value as follows:
let number = value.valueForKey("digits") as! String
From iOS9:
let number = value.stringValue
According to Apple's documentation on CNPhoneNumber:
stringValue
Property
The string value of the phone number. (read-only)
Declaration
SWIFT
var stringValue: String { get }

Related

UUID in Swift3, but "version 1" style UUID

This question is about Swift.
It's very easy to generate a rfc UUID in Swift getting a Swift String as at this stage Apple have made a Swift method for it...
func sfUUID()->String
{
return UUID().uuidString.lowercased()
}
I need an old-style "version 1" UUID, when using Swift
(Example: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_1_.28date-time_and_MAC_address.29)
Is there a way to do this in Swift3? ( >9 only)
In Swift, how to get a Version 1 UUID. So, there might be some option I don't know about on the UUID() call, or there's the difficulty of calling a C call and getting the result safely as a String.
Callam's link is the actual answer. Swift can (and in this case must) call C, so the name of the C function is all you really need.
But the "Swift" question here is just how to call a C function from Swift, which is a general skill that's more important than this particular question (and isn't really well explained in the current documentation). So it's worth studying how the following works, and not taking it as just the answer to "how do you generate a v1 UUID in Swift."
var uuid: uuid_t = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)
withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: 16) {
uuid_generate_time($0)
}
}
let finalUUID = UUID(uuid: uuid)
This is incredibly out of date. Don't do this any more.
I'd delete the answer, but it's ticked!
Swift code which gets to the C call...
func generateVersionOneAkaTimeBasedUUID() -> String {
// figure out the sizes
let uuidSize = MemoryLayout<uuid_t>.size
let uuidStringSize = MemoryLayout<uuid_string_t>.size
// get some ram
let uuidPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: uuidSize)
let uuidStringPointer = UnsafeMutablePointer<Int8>.allocate(capacity: uuidStringSize)
// do the work in C
uuid_generate_time(uuidPointer)
uuid_unparse(uuidPointer, uuidStringPointer)
// make a Swift string while we still have the C stuff
let uuidString = NSString(utf8String: uuidStringPointer) as? String
// avoid leaks
uuidPointer.deallocate(capacity: uuidSize)
uuidStringPointer.deallocate(capacity: uuidStringSize)
assert(uuidString != nil, "uuid (V1 style) failed")
return uuidString ?? ""
}

Can I use iOS9 Contacts Framework to get a formatted phone number?

I would like to be able to store a phone number in a standard way, e.g. just the digits (potentially with the '+' for the country code), something like these examples...
"17185555555"
"+17185555555"
"+447788888888"
... but I'd like to be able to DISPLAY it to a user in a properly formatted way, e.g.
"1 (718) 555-5555"
"+1 (718) 555-5555"
"+44 (7788) 888888"
...WITHOUT having to rely on a CNContactViewController to format it.
Obviously doing this just for US/Canada numbers would be easy - it's just one standard format - but I'd like it to be generic so it can work for numbers from any country. I know this question gives an answer for US/Can numbers only.
I know that I could use a CNContactViewController to display the number in the correct format, e.g.
let newContact = CNMutableContact()
newContact.givenName = "John"
newContact.familyName = "Smith"
newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberiPhone, value: CNPhoneNumber(stringValue:"17185555555"))]
let contactView = CNContactViewController(forContact: newContact)
self.presentViewController(contactView, animated: true, completion: nil)
This will show the number on screen properly formatted, i.e.
1 (718) 555-5555
... so I know that something in the framework can do it. (This approach works for other country phone number formats, as long as you prefix the number with the right country code - e.g. "+44...")
From various other questions I know that I can get the raw digits and country code out of a CNContact, e.g. (following above example)
for pNumber: CNLabeledValue in newContact.phoneNumbers {
let value = pNumber.value as! CNPhoneNumber
let cc = value.valueForKey("countryCode") as? String
let digits = value.valueForKey("digits") as? String
print("cc:" + cc + ", " + digits)
}
... but this will just show the unformatted string again - not what I am looking for in this case.
Any help or other recommended approaches really appreciated!
My answer proposes another lib
You can format your numbers with this lib.
And you can use like this:
let phoneNumber: NBPhoneNumber = try phoneUtil.parse("17185555555", defaultRegion: yourRegion)
let formattedString: String = try phoneUtil.format(phoneNumber, numberFormat: .E164)

Swift / XMLParser / How to parse a specific element / CheatyXML

I want to parse and download the current EUR - USD exchange rate. I have descided to get the value from the European Central Bank Feed.
I'm using the CheatyXML XMLParser extension.
How can I get the USD value?
With the following code, I get the value: "European Central Bank". My String is an optional on porpuse. Because my app crashed like 1 trillion times during finding the correct code to get the currency rate...
let feedUrl = NSURL(string: "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml")
let parser: XMLParser! = XMLParser(contentsOfURL: feedUrl!)
let exchangeString: String? = parser["gesmes:Sender"]["gesmes:name"].string // Returns an optional String
print(exchangeString)
How do I get the value of <Cube currency="USD" ?
let blogName: String? = parser["Cube"]["Cube"].string // Returns an optional String
Is not working.
Help is very appreciated.
You need to go one level deeper (there's three "Cube" fields), then get the attributes and finally subscript with the right key, for example:
parser["Cube"]["Cube"]["Cube"].attributes["currency"] as? String // "USD"
parser["Cube"]["Cube"]["Cube"].attributes["rate"] as? String // "1.1287"

How do I get Parse data as a String out of PFUser?

I am currently trying to get a value called "loot" out of the current user. I need the value as a String, but Swift is being stubborn and says it "cannot convert Anyobject to String". The Parse documentation for iOS says to use something like:
let score = gameScore["score"] as String
and so, I try this :
let lootAmount = user["loot"] as String
BTW 'user' is referring to the current user. When I try that, it gives error saying it's not convertible. I tried placing '!'s and '?'s wherever Xcode suggested, but it just crashed the app with no error.
So, how do I get the user value called "loot" as a String?
Loot is an NSNumber not an NSString or String.
You could convert it to a String like this:
if let loot = user["loot"] as? NSNumber {
let lootString = "\(loot)"
}
If you're not sure of an object's type, you can ask it using dynamicType:
print(user["loot"]!.dynamicType)
//prints `__NSCFNumber.Type`
You may need to downcast AnyObject. Try this: let lootAmount = user["loot"] as? String or unwrap your optional user if you haven't done so:
let currentUser = PFUser.currentUser()
if let user = currentUser {
let lootAmount = user["loot"] as String
}

Is it possible to convert a JSValue into an NSNumber?

This will show the following error: 'JSValue' is not convertible to 'NSNumber'. If it's not possible to convert, how should I go about getting the JSValue and assigning it to my NSNumber variable?
var sentences:NSNumber = getSentences.callWithArguments([])
According to the header file JSValue.h, you need to call toNumber() on your JSValue object. So it's probably:
var sentences:NSNumber = getSentences.callWithArguments([]).toNumber()
You can try:
if let sentences = getSentences.callWithArguments([]) as? NSNumber {
// consume sentences here
}
The if let structure is probably the simplest access to it since it may not actually BE a number, If that doesn't work, you'll have to go back to JavaScriptCore and call JSValueToNumber:
let sentences = getSentences.callWithArguments([])
let nSentences = JSValueToNumber(context, sentences, nil)

Resources