empty json reponse in Foursquare2 venue Explore ios api - ios

I'm working on iOS application with foursquare iOS api , I want to get the recommended near venues. I have used following code & it giving me an empty result .. Where have I done the mistake ? ? ?
NSArray* venues;
//get the foursquare locations
- (void)getTipsForLocation:(CLLocation *)location {
//NSLog(#"lat %f",location.coordinate.latitude);
[Foursquare2 venueExploreRecommendedNearByLatitude:#(location.coordinate.latitude)
longitude:#(location.coordinate.longitude)
near:nil
accuracyLL:nil
altitude:nil
accuracyAlt:nil
query:nil
limit:nil
offset:nil
radius:#(1500)
section:nil
novelty:nil
sortByDistance:1
openNow:0
venuePhotos:0
price:nil
callback:^(BOOL success, id result){
if (success) {
NSDictionary *dic = result;
venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc]init];
self.nearbyVenues = [converter convertToObjects:venues];
//NSLog(#"venues %#",venues);
//NSLog(#"near by places %#",self.nearbyVenues);
}
else{
NSLog(#" foursquare connecting error");
}
}];
NSLog(#"recommended place array %#",venues);
}

You Can Not pass Nil,In NSNumber & NSString.
NSNumber *emptynumber=[[NSNumber alloc] init];
[Foursquare2 venueExploreRecommendedNearByLatitude:lan longitude:lon near:#"" accuracyLL:emptynumber altitude:emptynumber accuracyAlt:emptynumber query:#"" limit:emptynumber offset:emptynumber radius:#(1500) section:#"" novelty:#"" sortByDistance:YES openNow:YES venuePhotos:YES price:#"" callback:^(BOOL success, id result) {
if (success) {
NSLog(#"secondResult: %#",result);
NSDictionary *dic = result;
NSArray *venues = [dic valueForKeyPath:#"response.venues"];
FSConverter *converter = [[FSConverter alloc] init];
self.venues = [converter convertToObjects:venues];
[self.tableView reloadData];
NSLog(#"Data: %#",venues);
}
}];
It Works For me.

Related

Convert message received from PubNub to Dictionary object

I have the following object C code for receiving PubNub message.
- (void)client:(PubNub *)client didReceiveMessage:(PNMessageResult *)message {
NSLog(#"Received message: %# on channel %# at %#", message.data.message,
message.data.subscribedChannel, message.data.timetoken);
}
The returned data is
Received message: (
{
key = userName;
value = Enoch;
},
{
key = photoID;
value = 3;
},
{
key = userID;
value = 1;
},
{
key = actionType;
value = chat;
},
{
key = message;
value = H;
}
) on channel chat at 14888810882049989
I would like to parse the message to a dictionary object for accessing the "value" by using the "key"
I am very new in objective C programming and don't know how to do.
Please help.
Loop through the message array and set the key value in dictionary.
NSArray *array = (NSArray*)message.data.message;
NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
for (NSDictionary *item in array) {
[dic setObject:[item objectForKey:#"value"] forKey:[item objectForKey:#"key"]];
}
NSLog(#"%#", dic);
Or
NSArray *array = (NSArray*)message.data.message;
NSArray *values = [array valueForKey: #"value"];
NSArray *keys = [array valueForKey: #"key"];
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:values forKeys:keys];
NSLog(#"%#", dic);
You can use below method for parsing your data and convert it into dictionary
ChatterBoxMessage *chatterBoxMessage = [[ChatterBoxMessage alloc] initFromDictionary: message.data.message withTimeToken: message.data.timetoken];
[chatterBoxMessage asDictionary];
By This method you will get dictionary.
Above ChatterBoxMessage is a PubNub library class.
Also you can parse your data like below :
for (NSDictionary *objectData in message.data.message) {
NSLog(#"Value : %#",objectData[#"value"]);
NSLog(#"Key : %#",objectData[#"key"]);
}

How to get Mobile Number from vCard String Objective C

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);
}

How do you get the "images" from a twitter feed to show in an iOS app

I have a code that accesses a Twitter feed and puts the text into a table. I then edited the code so I could display the text in my custom fashion in separate views, but I wanted to grab images from the tweets as well, and despite over an hour searching could not find a single reference. I have seen how to "Post" images, but to be clear, I need to get and "display" the images from the tweet in question.
Here are the highlights from my code that handles the Twitter Access:
-(void)twitterTimeLine
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES)
{
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts lastObject]; // last account on list of accounts
NSURL *requestAPI = [NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[parameters setObject:#"30" forKey:#"count"];
[parameters setObject:#"1" forKey:#"incude_entities"];
SLRequest *posts = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestAPI parameters:parameters];
posts.account = twitterAccount;
[posts performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
if (response)
{
// TODO: might want to check urlResponse.statusCode to stop early
NSError *jsonError; // use new instance here, you don't want to overwrite the error you got from the SLRequest
NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
if (array) {
if ([array isKindOfClass:[NSArray class]]) {
self.array = array;
NSLog(#"resulted array: %#",self.array);
}
else {
// This should never happen
NSLog(#"Not an array! %# - %#", NSStringFromClass([array class]), array);
}
}
else {
// TODO: Handle error in release version, don't just dump out this information
NSLog(#"JSON Error %#", jsonError);
NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"Received data: %#", dataString ? dataString : response); // print string representation if response is a string, or print the raw data object
}
}
else {
// TODO: show error information to user if request failed
NSLog(#"request failed %#", error);
}
self.array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
if (self.array.count != 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData]; // this part loads into table - important!
});
}
}];
}
}
else
{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
and here is how I display the Tweet
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID = #"cellID";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
NSDictionary *tweet = _array[indexPath.row];
cell.textLabel.text = tweet[#"text"];
//NSString *element = [myArray objectAtIndex:2];
//NSString *element = myArray[2];
// I created some custom views to show the text, but kept the table for testing purposes
TemplateView *tempView = [viewArray objectAtIndex:testCounter];
tempView.TweetView.text = tweet[#"text"];
// -> this was what I was hoping for // tempView.ContentView.image = tweet[#"image"];
testCounter++;
if (testCounter >= 30)
{
testCounter = 0;
}
return cell;
}
I took out the key lines that I think is where I need to look:
tempView.TweetView.text = tweet[#"text"];
tempView.ContentView.image = tweet[#"image"];
// hoping that the latter would work as the first one does, but clearly it's not that simple
This might not be possible, if so, how would I get the images from the "link" (url) and make sure it is an image and not a video or other website?
I could set up a "word search" to grab text starting with http from the tweet and hopefully generate a URL from the string
TwitterKit doesn't seem to support images publicly.. I'm having the same stupid issue. The API internally holds images when using the built in tableview and datasource.. It requires a listID and a Slug.. However, when you want the images via JSON, you are out of luck! Even TWTRTweet object doesn't have entities or media properties!
Not sure how anyone can develop such an awful API.. In any case, I reversed the server calls made internally and found that it sends other "undocumented" parameters..
Example:
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSString *endpoint = #"https://api.twitter.com/1.1/statuses/user_timeline.json";
NSDictionary *params = #{#"screen_name":#"SCREEN_NAME_HERE",
#"count": #"30"};
will return NO MEDIA.. even if you have #"include_entities" : #"true".
Solution:
TWTRAPIClient *client = [[TWTRAPIClient alloc] init];
NSString *endpoint = #"https://api.twitter.com/1.1/statuses/user_timeline.json";
NSDictionary *params = #{#"screen_name":#"SCREEN_NAME_HERE",
#"count": #"30",
#"tweet_mode": #"extended"};
With tweet_mode set to extended (tweet_mode is an undocumented parameter), it will now return the media as part of the response.. This includes the "type" which is "photo" for images.
We can get tweets with images by applying "filter=images" query with "include_entities=true". It'll give tweets with media entities, under which we can see type="photo" and other related data.
For ex:
https://api.twitter.com/1.1/search/tweets.json?q=nature&include_entities=true&filter=images
Try this query at twitter developer console and see the response format: https://dev.twitter.com/rest/tools/console
Hope this will help.

Parsing JSON information in Objective C (multiple levels)

I'm able to parse a part of my JSON file but if I want to go deeper in the structure, I'm lost. Here's my JSON :
{
"album":[
{
"album_titre":"Publicité",
"album_photo":"blabla.jpg",
"album_videos":[
{
"titre_video":"Chauffage Compris",
"duree_video":"01'25''",
"photo_video":"chauffage.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2012",
"duree_video":"01'43''",
"photo_video":"nifff.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Events",
"album_photo":"bloublou.jpg",
"album_videos":[
{
"titre_video":"Auvernier Jazz",
"duree_video":"01'15''",
"photo_video":"auvernier.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2011",
"duree_video":"01'03''",
"photo_video":"nifff2011.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Culture",
"album_photo":"bilibl.jpg"
},
{
"album_titre":"Postproduction",
"album_photo":"bizoubzou"
}
]
}
And here's my objective-c code :
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (document==nil)
{
NSLog( #"oops\n%#", error);
}
NSArray *album = document[#"album"];
for( NSDictionary *albumDictionary in album )
{
[album_titre addObject:albumDictionary[#"album_titre"]];
[album_photo addObject:albumDictionary[#"album_photo"]];
for( NSDictionary *album_videosDictionary in albumDictionary[#"album_videos"])
{
[titre_video addObject:album_videosDictionary[#"titre_video"]];
[duree_video addObject:album_videosDictionary[#"duree_video"]];
[photo_video addObject:album_videosDictionary[#"photo_video"]];
[lien_video addObject:album_videosDictionary[#"lien_video"]];
}
}
[self.tableView reloadData];
}
What I can't achieve is to create an array with for example contains all "titre_video" corresponding to "album_titre":"publicité". So it should contain "Chauffage Compris" and "Nifff 2012".
I know it's a kind of easy question but I've search for a while and still not able to do it.
Thank's a lot.
Nicolas
The key is to understand JSON structure:
{ } - - this means the underlying object is a dictionary.
[ ] -- this means the underlyingobject is an array
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
// all titre:video for album_titre:publicite
NSArray *albumArray = [document objectForKey:#"album"];
NSDictionary *dict = [albumArray objectAtindex:0];
NSArray *videos = [dict objectForKey:#"album_videos"];
// to fetch Videos inside album_videos
// here you will get al the videos inside key titre_video
NSMutableArray *titreVideoArray = [[NSMutableArray alloc]init];
for(int i=0; i< videos.count; i++){
NSDictionary *dict = [videos objectAtindex:i];
NSArray *titreVideos = [dict objectForKey:#"titre_video"];
[titreVideoArray addObject: titreVideos];
}
}
It seems you want to fetch all the videos relating to different "album_titre".
I would suggest you to use NSPredicate .
NSArray *videos = [self videosArrayForTitle:#"Publicité" albumArray:albumArray];
Here we pass title and the albumArray from above to fetch us the videos array.
- (NSArray *)videosArrayForTitle:(NSString *)title albumArray:(NSArray *)albumArray{
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"SUBQUERY(album_titre, $content, $content CONTAINS %#).#count > 0", title];
NSArray *searchResults=[albumArray filteredArrayUsingPredicate:resultPredicate];
NSArray *videos = [searchResults objectForKey:#"album_videos"];
return videos;
}
{ } denotes NSDictionary
[ ] denotes NSArray
Copy your json into a text edit file and go in deep. You can use NSLog() to print the data, when you go deep.
Hope it will help you.

XML into JSON conversion in iOS

I need to convert XML response to JSON and sand to the json To javaScript code.
My XML response:
<cell>
<Result>True</Result>
<sguid>02291c402-2220-422b-b199-f92f22e56d2f</sguid>
</cell>
I am using XMLReader supporting file from this site:
XMLReader
I am using this code to convert XML to JSON :
+ (NSString*) XMLToJson:(CXMLDocument *)xmlDocument
{
NSError *error = nil;
NSArray *resultNodes = [xmlDocument nodesForXPath:#"//cell" error:&error];
if(error)
NSLog(#"%#",error.description);
CXMLNode *cellNode = [resultNodes objectAtIndex:0];
NSLog(#"%#",cellNode.XMLString);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:cellNode.XMLString error:&parseError];
NSLog(#"%#", xmlDictionary);
//{print this.
// cell = {
// Result = {
// text = True;
// };
// sguid = {
// text = "0391c402-1120-460b-b199-f92fffe56d2f";
// };
// };
//}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if(error)
NSLog(#"%#",error.description);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
return jsonString;
}
I got JSON response like this:
{
"cell" : {
"Result" : {
"text" : "True"
},
"sguid" : {
"text" : "0391c402-1120-460b-b199-f92fffe56d2f"
}
}
}
I need JSON response like this:
{
"cell": {
"Result": "True",
"sguid": "02291c402-2220-422b-b199-f92f22e56d2f"
}
}
Because then I send this json to javascript code I get that exception jquery mobile dont know parser this and throws an exception of syntax error.
I've seen programmers use this solution and is helping them but I still get the same result in this solution.
XML into JSON conversion in iOS
thanks
I just wrote a function for your problem, I tried it on with a couple of XMLs. Let me know if you find any issues
- (NSMutableDictionary *)extractXML:(NSMutableDictionary *)XMLDictionary
{
for (NSString *key in [XMLDictionary allKeys]) {
// get the current object for this key
id object = [XMLDictionary objectForKey:key];
if ([object isKindOfClass:[NSDictionary class]]) {
if ([[object allKeys] count] == 1 &&
[[[object allKeys] objectAtIndex:0] isEqualToString:#"text"] &&
![[object objectForKey:#"text"] isKindOfClass:[NSDictionary class]]) {
// this means the object has the key "text" and has no node
// or array (for multiple values) attached to it.
[XMLDictionary setObject:[object objectForKey:#"text"] forKey:key];
}
else {
// go deeper
[self extractXML:object];
}
}
else if ([object isKindOfClass:[NSArray class]]) {
// this is an array of dictionaries, iterate
for (id inArrayObject in (NSArray *)object) {
if ([inArrayObject isKindOfClass:[NSDictionary class]]) {
// if this is a dictionary, go deeper
[self extractXML:inArrayObject];
}
}
}
}
return XMLDictionary;
}
And use it like this
NSDictionary *clearXML = [[self extractXML:[yourParsedXMLDictionary mutableCopy]] copy];
Your problem in using XMLReader. For resolve this problem you can use XMLConverter instead of the XMLReader.

Resources