How to get Mobile Number from vCard String Objective C - ios

I am working on Action Extension Objective C. I have successfully created Extension for share recent contact in my Extension. In that I am getting v Card String. How can I get Mobile Number from v Card String. Any help would be appreciated.

Using contactsWithData:error: class method of CNContactVCardSerialization, you can retrieve info from a vCard.
It's from Contacts.framework, available since iOS9.
For earlier version, you can use AddressBook.framework. You can read info here.
NSError *errorVCF;
NSArray *allContacts = [CNContactVCardSerialization contactsWithData:[contactStr dataUsingEncoding:NSUTF8StringEncoding] error:&errorVCF];
if (!errorVCF)
{
NSMutableString *results = [[NSMutableString alloc] init];
//NSLog(#"AllContacts: %#", allContacts);
for (CNContact *aContact in allContacts)
{
NSArray *phonesNumbers = [aContact phoneNumbers];
for (CNLabeledValue *aValue in phonesNumbers)
{
CNPhoneNumber *phoneNumber = [aValue value];
[results appendFormat:#"%# %#\n", [aValue label], [phoneNumber stringValue]];
}
}
NSLog(#"Final: %#", results);
}

Related

Corruption of NSString or encoding issue in Objective C

Please see code below:
+ (void)splashDataFromJSON:(NSData *)objectNotation error:(NSError **)error
{
NSError *localError = nil;
NSDictionary *parsedObject = [NSJSONSerialization JSONObjectWithData:objectNotation options:0 error:&localError];
if (localError != nil) {
*error = localError;
}
NSMutableArray* btms = [[NSMutableArray alloc] init];
NSMutableDictionary* btmManufacturerResolutionDictionary = [[BTMCache sharedManager] btmManufacturerResolutionDictionary];
NSArray *results = [parsedObject valueForKey:#"results"];
NSLog(#"Count %d", parsedObject.count);
NSString* imageBaseUrl = [[parsedObject valueForKey:#"general"] valueForKey:#"image_base_url"];
imageBaseUrl = [imageBaseUrl stringByAppendingString:#"hdpi/"];
NSString* splashImageName = [[[parsedObject valueForKey:#"general"] valueForKey:#"splash"] valueForKey:#"img"];
NSString* splashAdvertiserURL = [[[[parsedObject valueForKey:#"general"] valueForKey:#"splash"] valueForKey:#"url"] copy];
NSMutableString* appendedString = [[NSMutableString alloc] init];
for(int i =0 ;i<[splashAdvertiserURL length]; i++) {
char character = [splashAdvertiserURL characterAtIndex:i];
printf(&character);
sleep(0.1);
if (character != "!")
{
[appendedString appendFormat:#"%c", character];
}
}
[[SplashData sharedManager] setSplashAdvertiserURL:appendedString];
[[SplashData sharedManager] setSplashImageName:splashImageName];
splashAdvertiserURL = [[SplashData sharedManager] splashAdvertiserURL];
}
The point of interest is in splashAdvertiserURL. When I receive this data and print it out using po, it comes out as "https://radar.com/ref/go/84/". This is fine and what was expected. When I look at the incoming data in JSONLint it looks like this:
"general": {
"image_base_url": "https:\/\/radar.com\/img\/manufacturers\/",
"splash": {
"img": "image1.png",
"url": "https:\/\/radar.com\/ref\/go\/84\/"
}
},
As you can see, further on I put the NSString into a singleton with an NSString property. Nothing abnormal here. I then proceed to retrieve it to see that all is ok. Further to this the program continues. In another class I wish to retrieve this information, and when I try and do that, it throws EXC_BAD_ACCESS. There appears to be garbage in there.
I then put in a loop in the code as you can see to print out the characters one at a time. Very curiously, when I print that out using po I get:
https://
r
a
d
ar.com/ref/go/8 4!/"
Exactly in that format. If I then proceed to hardcode the string https://radar.com/ref/go/84/ - including escape characters and everything, then all works fine. No issues. If I handle a normal string incoming without escape characters it stores fine in the singleton as well, no issue. enter code here
I am pretty stumped here as to what is going on. Can someone assist?
Thank you
For URL you received as string you need to encode before use it to in your app. Have a look at below code:
NSString *sampleUrl = #"https:\/\/radar.com\/ref\/go\/84\/";
NSString *encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];

Show Location string using latitude and longitude

I am using this method to show the string of location using current location latitude and longitude but it is showing differently
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false",location.coordinate.latitude, location.coordinate.longitude];
NSError* error;
NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
NSData *data = [locationString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *dic = [[json objectForKey:#"results"] objectAtIndex:0];
NSArray* arr = [dic objectForKey:#"address_components"];
//Iterate each result of address components - find locality and country
NSString *cityName;
NSString *countryName;
for (NSDictionary* d in arr)
{
NSArray* typesArr = [d objectForKey:#"types"];
NSString* firstType = [typesArr objectAtIndex:0];
if([firstType isEqualToString:#"locality"])
cityName = [d objectForKey:#"long_name"];
if([firstType isEqualToString:#"country"])
countryName = [d objectForKey:#"long_name"];
}
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
but final location is showing this type :-
Final Location नठदिलà¥à¤²à¥,India
Why it is showing this type? Can anyone know about this.
Please supply the language with the API params. If language is not supplied, the geocoder attempts to use the preferred language as specified in the Accept-Language header, or the native language of the domain from which the request is sent.
So please replace the code as with the language parameter as like this.
NSString *urlString = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?latlng=%f,%f&sensor=false&language=en",location.coordinate.latitude, location.coordinate.longitude];
and try again.
I believe that is an uninitialzed variable which is pointing into random memory.
Try:
NSString *cityName = nil;
NSString *countryName = nil;
Short-circuit your for loop:
for (NSDictionary* d in arr)
{
// Add this after the existing code:
if (cityName && countryName)
break;
}
and check for errors before presenting the results:
if (cityName && countryName) {
NSString* locationFinal = [NSString stringWithFormat:#"%#,%#",cityName,countryName];
NSLog(#"Final Location %# ",locationFinal);
} else {
NSLog(#"Failed to find location");
}
Finally your JSON-processing code does no error-checking at all. That's a mistake.

Save json object in sqlite like text and retransform to dictionary on read

I want to save a Json Object in a field (text) sqlite and then read it again with a select and retransform to NSDictionary or NSMutableArray to parse the key/values
This is how i save actually in the sqlite DB
As you see, is a song object from the iTunes api. I want to read that object and parse it.
This is how i make the select query and save it in a NSDictionary while i filling and NSMutableArary
globals.arrayMyPlaylists = [[NSMutableArray alloc] init];
// Form the query.
NSString *query = #"select * from myplaylists";
// Get the results.
NSArray *listas = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query]];
for (int i = 0; i < listas.count; i++) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
NSLog(#"lista %d %# %#", i, listas[i][0], listas[i][1]);
[dictionary setObject:listas[i][0] forKey:#"id"];
[dictionary setObject:listas[i][1] forKey:#"nombre"];
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
[dictionary setObject:canciones forKey:#"canciones"];
[globals.arrayMyPlaylists addObject:dictionary];
dictionary = nil;
}
When i try to read it in the cellForRowAtIndexPath method
NSArray *canciones = [[NSArray alloc] initWithArray:[[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"canciones"]];
and try to get the value for the key artworkUrl100
[cell.tapa1 sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", [[canciones objectAtIndex:i] valueForKey:#"artworkUrl100"]]] placeholderImage:nil];
i get the error
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSCFString 0x7ff575810600> valueForUndefinedKey:]: this class is not key value coding-compliant for the key artworkUrl100.'
i understand i'm messing up in some way with dictionarys/nsmutablearrays. I need some help. Thanks!
EDIT: this is how i save the data in the DB
NSString *query = [NSString stringWithFormat:#"insert into canciones (idplaylist, cancion) values ('%#', '%#')", [[globals.arrayMyPlaylists objectAtIndex:indexPath.row] valueForKey:#"id"], self.elementoSeleccionado];
[self.dbManager executeQuery:query];
self.elementoSeleccionado is the NSMutableArray with the "cancion" object and it's saved like it's shows the first image.
EDIT 2: this is what i get trying schmidt9's answer
EDIT 3: OK, i have the json string escaped. How i have to parse now?
You should parse your output first with NSJSONSerialization:
NSString *query2 = [NSString stringWithFormat:#"select cancion from canciones where idplaylist = %#", listas[i][0]];
NSArray *canciones = [[NSArray alloc] initWithArray:[self.dbManager loadDataFromDB:query2]];
// I suppose your array canciones should contain only one song object ...
NSError *error = nil;
id object = [NSJSONSerialization JSONObjectWithData:canciones[0] options:0 error:&error];
if(error) {
// handle error ...
}
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *result = object;
[dictionary setObject:result forKey:#"canciones"];
}
Edit
Saving to database
2 options:
- if you get a prepared json string, save it directly to DB, but before you should escape quotes. See eg. here
- if you have NSDictionary:
- (NSString*)JSONStringWithDictionary:(NSDictionary*)dictionary prettyPrinted:(BOOL)prettyPrinted
{
NSJSONWritingOptions options = (prettyPrinted) ? NSJSONWritingPrettyPrinted : 0;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:options error:nil];
return [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];
}
After that you should escape the string too.

iOS FGallery objective c assigning string value dynamically

It is a bit complicated to explain my problem. I am using FGallery library https://github.com/gdavis/FGallery-iPhone and especially its feature to load images from URL addresses. When I hardcode the URL path it works super, but wen I pass a string variable to the class which I have created it doesn't work. I tried to debug it and it seems that everything is ok, there is a string assigned to the variable and everything, but do not show the picture. I am doing this in a loop and using ARC.
-(void) loadSoftia
{
//======================================================================================
//THIS WORKS CORRECTLY!!!
wcSofia = [[NSMutableArray alloc] init];
Webcam *s1 = [[Webcam alloc]init];
s1.description=#"Sofia";
s1.location = #"http://www.ampthillweatherstation.info/currentweather/webcamimage.jpg";
[wcSofia addObject:s1];
//======================================================================================
NSMutableString *urlGetOthersLocations =[NSMutableString stringWithFormat:#"http://%#/WebHandlers/%#", #"192.168.188.204", #"BGCam.ashx"];
ServerResponse *serverResponseOthersLocations = [HelperViewController getJsonDataFromTheServer:urlGetOthersLocations];
if(serverResponseOthersLocations.data!=nil)
{
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:serverResponseOthersLocations.data
options:NSJSONReadingMutableLeaves|NSJSONReadingMutableContainers
error:nil];
[wcSofia removeAllObjects];
Webcam *wc;
int i=0;
for (NSDictionary *locationsDic in dic){
NSString *key;
for ( key in locationsDic) {
NSLog(#"%# = %#", key, [locationsDic objectForKey: key]);
}
NSLog(#"%#", [locationsDic objectForKey:#"URL"]);
NSLog(#"%# = %#", locationsDic, [locationsDic objectForKey: locationsDic]);
NSString *url =[locationsDic objectForKey:#"URL"];
// NSLog(#"%#", url);
NSMutableString* theString = [NSString stringWithFormat:#"%i ",i];
wc = [[Webcam alloc]initWithLocation: [NSString stringWithFormat:#"%#", url] withDescription:#"description"];
wc.location = url;//DOESNT WORK!
wc.description =#"София";// theString;//[NSString stringWithFormat:#"%#", #"aa"]; // #"София";
wc.location = #"http://media.borovets-bg.com/cams/channel?channel=61";//IT WORKS BECAUSE IT IS HARDCODED
if(wcSofia!=nil)
{
[wcSofia addObject:wc];
NSLog(#"%#", wc.location);
}
i++;
}
}
}
I have commented a section of the code which works and which doesn't.
I suppose that you are not going to need the whole program, because it make requests to my local web server to get the URL addresses and descriptions, but trust me this thing works perfect.
Thank you for your help in solving that mystery.
Edit:
Complete source Code: https://dl.dropboxusercontent.com/u/46512232/FGallery.zip

Pull out valueForKeys of an inner NSMutableDictionary iOS

Ok I get and store a Json feed to an array called jsonArray. I then loop over the jsonArray pulling out the array keys and storing them as strings. I then add those strings to an inner dictionary called innerDict, I then add that dictionary to the info dictionary with the key thePostCode using the below. So basically innerDict is stored inside infoDict.
-(void)pointInfo{
infoDict = [[NSMutableDictionary alloc]init];
for (int i = 0; i < jsonArray.count; i++) {
innerDict = [[NSMutableDictionary alloc]init];
info = [[jsonArray objectAtIndex:i]objectForKey:#"inf"];
thePostCode = [[jsonArray objectAtIndex:i]objectForKey:#"pc"];
mail = [[jsonArray objectAtIndex:i]objectForKey:#"mail"];
url = [[jsonArray objectAtIndex:i]objectForKey:#"url"];
type = [[jsonArray objectAtIndex:i]objectForKey:#"items"];
[innerDict setObject:type forKey:#"Items"];
[innerDict setObject:info forKey:#"Info"];
[innerDict setObject:mail forKey:#"Mail"];
[innerDict setObject:url forKey:#"Url"];
[infoDict setObject:innerDict forKey:thePostCode];
}
the output of infoDict looks like this:
infoDict is {
"ME14 4NN" = {
Info = "";
Items = 4;
Mail = "";
Url = "";
};
"ME15 6LG" = {
Info = af;
Items = "0,6,9";
Mail = "";
Url = "";
};
"ME15 6YE" = {
Info = "";
Items = "4,5,6,7,11";
Mail = "";
Url = "";
};
}
Now what I want to do is get the values of the innerDict object i.e "ME15 6YE" above and use that as the query to pull out the associated data for Info, Items, Mail and Url keys. I have been staring at my screen for a few hours but I am just not getting it.
I can pull out the last object of the inner dict using the below however I would like to grab all the values associated with a particular postcode which would be the innerDict key. Completely brain fried at the moment!
for (NSMutableDictionary *dictionary in infoDict) {
NSLog(#"URL %#", [innerDict objectForKey:#"Url"]);
NSLog(#"MAIL %#", [innerDict objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [innerDict objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [innerDict objectForKey:#"Info"]);
}
To get the correct inner dictionary, use objectForKey:
NSDictionary *innerDict = [infoDict objectForKey:#"ME15 6YE"];
NSLog(#"Url %#", [innerDict objectForKey:#"Url"]);
NSLog(#"Mail %#", [innerDict objectForKey:#"Mail"]);
NSLog(#"Items %#", [innerDict objectForKey:#"Items"]);
NSLog(#"Info %#", [innerDict objectForKey:#"Info"]);
Maybe I'm misunderstanding something, but I think this should answer your questions.
You're using dictionary in the for loop, but trying to access it via innerDict. Change it to:
for (NSMutableDictionary *dictionary in infoDict) {
NSLog(#"URL %#", [dictionary objectForKey:#"Url"]);
NSLog(#"MAIL %#", [dictionary objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [dictionary objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [dictionary objectForKey:#"Info"]);
}
Or, for a single one,
NSMutableDictionary *inner = [infoDict objectForKey:#"POST CODE HERE"];
NSLog(#"URL %#", [inner objectForKey:#"Url"]);
NSLog(#"MAIL %#", [inner objectForKey:#"Mail"]);
NSLog(#"ITEMS %#", [inner objectForKey:#"Items"]);
NSLog(#"ITEMS %#", [inner objectForKey:#"Info"]);

Resources