That's an example
{
"updated":1350213484,
"id":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson",
"title":"Risultati di feed per \"Prova\"",
"self":[
{
"href":"http://www.google.com/reader/api/0/feed-finder?q\u003dProva\u0026output\u003djson"
}
],
"items":[
{
"title":"Home Page - La prova del cuoco",
"id":"http://www.laprovadelcuoco.rai.it/",
"updated":1350213485,
"feed":[
{
"href":"http://www.laprovadelcuoco.rai.it/dl/portali/site/page/Page-ffb545b4-9e72-41e5-866f-a465588c43fa-rss.html"
}
],
"alternate":[
{
"href":"http://www.laprovadelcuoco.rai.it/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Diventa un cuoco provetto con “La Prova del Cuoco”: le videoricette in un' applicazione di facile e veloce consultazione per il tuo Iphone. Scopri come acquistare ..."
}
},
{
"title":"Le prove Invalsi di matematica e italiano",
"id":"http://online.scuola.zanichelli.it/quartaprova/",
"updated":1350213486,
"feed":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/feed/"
}
],
"alternate":[
{
"href":"http://online.scuola.zanichelli.it/quartaprova/",
"type":"text/html"
}
],
"content":{
"direction":"ltr",
"content":"Un sito Zanichelli dedicato alle prove Invalsi di italiano e matematica: esercitazioni, consigli, informazioni utili, novità, aggiornamenti e blog d'autore sulle prove ..."
}
},
How can I get the feed URL?
That's what I do
NSString *daParsare=[reader searchFeed:searchText];
NSArray *items = [[daParsare JSONValue] objectForKey:#"items"];
for (NSDictionary *item in items) {
NSString *title = [item objectForKey:#"title"];
NSString *feed = [item valueForKeyPath:#"feed.href"];
}
[tab reloadData];
With the title everything is ok but when I try to access to the feed paramater I get the error...
Assuming your JSON object is named jsonObject, you would simply access the href element. So, in your current object, the URL is in an object named href, which is the first (and in this case, only) element in an array named feed at the top level:
NSString* urlString = jsonObject[#"feed"][0][#"href"];
You should check to make sure that if feed exists, it's not an empty array before you access one of its elements.
NSString *feed = [item valueForKeyPath:#"feed.href"];
is wrong, as feed refers to an array, that again holds a dictionary.
NSString *feed = [[[item objectForKey:#"feed"] objectAtIndex:0] objectForKey:#"href"];
If you are using an modern Xcode, this last line is the same as in Jason Cocos answer.
NSString* feed = item[#"feed"][0][#"href"];
this syntax is called Object Subscription.
Related
I am trying to retrieve as much text as I can from the users emails from the gmail api. I have successfully retrieved the thread list id, the thread id, the history id, and a snippet of text from the thread aka email. What Im trying to accomplish to only retrieve a snippet of text from the thread or email, or possibly all the text from the thread of email. Here is my code so far and the restults I
- (void)fetchThreads{
self.output.text = #"\n Getting threads...";
// NSString *threadID = #"15fb742b462acbdc";
// NSString *threadID1 = #"15f56dc58e92f914";
// NSString *messageID = #"0x600000453020";
GTLRGmailQuery_UsersThreadsList *query = [GTLRGmailQuery_UsersThreadsList queryWithUserId:#"me"];
query.q = #"in:drafts";
query.userId = #"me";
self.service.shouldFetchNextPages = true;
NSLog(#"The number is 1");
[self.service executeQuery:query
delegate:self
didFinishSelector:#selector(displayResultWithTicket2:finishedWithObject:error:)];
}
- (void)displayResultWithTicket2:(GTLRServiceTicket *)ticket finishedWithObject:(GTLRGmail_ListThreadsResponse *)threadResponse
error:(NSError *)error {
if (error == nil) {
NSMutableString *threadString = [[NSMutableString alloc] init];
if (threadResponse.threads.count > 0) {
[threadString appendString:#"Labels:\n"];
for (GTLRGmail_Thread *thread in threadResponse.threads) {
[threadString appendFormat:#"\n This is message %# \n", thread];
}
} else {
[threadString appendString:#"No labels found."];
NSLog(#"The eror is %#", error.localizedDescription);
}
self.output.text = threadString;
} else {
[self showAlert:#"Error" message:error.localizedDescription];
}
}
Results:
This is message GTLRGmail_Thread 0x604000259200: {id:"15f500862dbcee7b" snippet:"Coffin of Ankhefenmut Author: John Smith Professor: Ms. Strum Course: Survey of Art in the Western World I, ARH170 Due Date: 10/24/17 The Ancient Egyptians are one of the worlds oldest civilizations" historyId:"2636014"}
This is message GTLRGmail_Thread 0x604000259470: {id:"15f02e206c54b910" snippet:"A Review of Alice Goffman's “On the Run” Alice Goffman's “On the Run” is a well-conducted sociological and ethnographical incite into the lives of young black youth during the “Tough on Crime”" historyId:"2636016"}
This is message GTLRGmail_Thread 0x60400024ec70: {id:"15ec4d1581e8bf30" snippet:" Introduction to Social Research - Ms. Wynn | Due 9/28/17 | 001261311 The Tearoom Trade Study Review The sociologist Laud Humphrey's conducted a very controversial study in the" historyId:"2406852"}
You'll have to implement this on Objective-C. Using the Users.messages.get, just place the "snippet" property as 'fields' parameter. This will return the snippet response only.
A sample response from the Try-it applying that:
{
"snippet": "Your script, testscript, has recently failed to finish successfully."
}
OmniFocus has a Cocoa Service that allows you to create tasks based upon selected items.
It has a preference that allows you to set the keyboard shortcut that triggers the Service. This is not just a global hotkey, it's a bona fide Service that shows up in the menu.
You can the keyboard shortcut to pretty much any combination, including combinations with ⌥ and ^. This functionality is not documented - the docs seem to say that KeyEquivalents must be a ⌘+[⇧]+someKey.
Once this is set, I observe three things:
The OmniFocus Info.plist file does not contain a KeyEquivalent listed. This is not surprising, as the file is read-only.
The pbs -dump_pboard utility lists NSKeyEquivalent = {}; for the service.
Using NSDebugServices lists this interesting line that does not show up with most debugging sessions (Obviously, for keyboard shortcut ⌃⌥⌘M): OmniFocus: Send to Inbox (com.omnigroup.OmniFocus) has a custom key equivalent: <NSKeyboardShortcut: 0x7fb18a0d18f0 (⌃⌥⌘M)>.
So my questions are twofold, and I suspect they are related:
How do you dynamically change a service's KeyEquivalent?
How do you set the KeyEquivalent to a combination including ⌃ and ⌥
Thank you!
Figured it out. The basic process is described here: Register NSService with Command Alt NSKeyEquivalent
The code is this:
//Bundle identifier from Info.plist
NSString* bundleIdentifier = #"com.whatever.MyApp";
//Services -> Menu -> Menu item title from Info.plist
NSString* appServiceName = #"Launch My Service";
//Services -> Instance method name from Info.plist
NSString* methodNameForService = #"myServiceMethod";
//The key equivalent
NSString* keyEquivalent = #"#~r";
CFStringRef serviceStatusName = (CFStringRef)[NSString stringWithFormat:#"%# - %# - %#", bundleIdentifier, appServiceName, methodNameForService];
CFStringRef serviceStatusRoot = CFSTR("NSServicesStatus");
CFPropertyListRef pbsAllServices = (CFPropertyListRef) CFMakeCollectable ( CFPreferencesCopyAppValue(serviceStatusRoot, CFSTR("pbs")) );
// the user did not configure any custom services
BOOL otherServicesDefined = pbsAllServices != NULL;
BOOL ourServiceDefined = NO;
if ( otherServicesDefined ) {
ourServiceDefined = NULL != CFDictionaryGetValue((CFDictionaryRef)pbsAllServices, serviceStatusName);
}
NSUpdateDynamicServices();
NSMutableDictionary *pbsAllServicesNew = nil;
if (otherServicesDefined) {
pbsAllServicesNew = [NSMutableDictionary dictionaryWithDictionary:(NSDictionary*)pbsAllServices];
} else {
pbsAllServicesNew = [NSMutableDictionary dictionaryWithCapacity:1];
}
NSDictionary *serviceStatus = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kCFBooleanTrue, #"enabled_context_menu",
(id)kCFBooleanTrue, #"enabled_services_menu",
keyEquivalent, #"key_equivalent", nil];
[pbsAllServicesNew setObject:serviceStatus forKey:(NSString*)serviceStatusName];
CFPreferencesSetAppValue (
serviceStatusRoot,
(CFPropertyListRef) pbsAllServicesNew,
CFSTR("pbs"));
Boolean result = CFPreferencesAppSynchronize(CFSTR("pbs"));
if (result) {
NSUpdateDynamicServices();
NSLog(#"successfully installed our alt-command-r service");
} else {
NSLog(#"couldn't install our alt-command-r service");
}
If the code succeeds, you can view this in ~/Library/Preferences/pbs.plist
You should see something like:
NSServicesStatus = {
"com.whatever.MyApp - Launch My Service - myServiceMethod" = {
enabled_context_menu = :true;
enabled_services_menu = :true;
key_equivalent = "#~r";
};
I'm trying to get the directions using google directions but I'm getting this error :
Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised
leading character (41)\
Here is the Json
loadDirections('Avenida Paulista', 'Rua Augusta', { 'locale': 'en', travelMode: G_TRAVEL_MODE_WALKING, avoidHighways: false, getPolyline: true, getSteps: true, preserveViewport: false})
Whats is wrong? Whats Unrecognised leading character (41) mean?
- (void)loadWithStartPoint:(NSString *)startPoint endPoint:(NSMutableArray *)endPoints options:(UICGDirectionsOptions *)options {
for (int idx = 0; idx < [endPoints count];idx ++)
{
NSString* msg = [NSString stringWithFormat:#"loadDirections('%#', '%#', %#)", startPoint, [endPoints objectAtIndex:idx], [options JSONRepresentation]];
NSLog(#"msg %#",msg);
mstr = [msg retain];
[self performSelector:#selector(loadDirections:) withObject:nil afterDelay:0.5];
}
}
-(void)loadDirections:(NSString *)message
{
[googleMapsAPI stringByEvaluatingJavaScriptFromString:mstr];
}
The JSON is invalid.
{
'locale': 'en',
travelMode: "G_TRAVEL_MODE_WALKING",
avoidHighways: false,
getPolyline: true,
getSteps: true,
preserveViewport: false
}
I think this has something to do with G_TRAVEL_MODE_WALKING, it should be in quotes. The only valid JSON values are as follows
Objects ({})
Arrays ([])
Value
String ("this is a string")
Number 1/-1
true
false
null
JSON Documentation
Make sure that, while initializing the GDirections object, you also pass an actual element as the second parameter.
As stated in the documentation:
The mode of travel, such as driving (default) or walking. Note that if
you specify walking directions, you will need to specify a panel
to hold a warning notice to users.
If you are using the Map-Kit-Route-Directions extensions, you just have to open the api.html file and, at line 16, substitute this
gdir = new GDirections(null, null);
with this
gdir = new GDirections(null, "body");
Is it possible/Is there a file attribute to get the date, when a file was added to the mobile documents folder/icloud?
I've found the answer in another question here at stackoverflow:
Where does the Finder obtain the "date added" of an item in a folder?
The date-added attribute is in the Spotlight metadata:
NSDate *dateAdded(NSURL *url)
{
NSDate *rslt = nil;
MDItemRef inspectedRef = nil;
inspectedRef = MDItemCreateWithURL(kCFAllocatorDefault, (CFURLRef)url);
if (inspectedRef){
CFTypeRef cfRslt = MDItemCopyAttribute(inspectedRef, (CFStringRef)#"kMDItemDateAdded");
if (cfRslt) {
rslt = (NSDate *)cfRslt;
}
}
return rslt;
}
I am constructing a tuning fork app. The fork should allow up to 12 preset pitches.
Moreover, I wish to allow the user to choose a theme. Each theme will load a set of presets (not necessary to use all of them).
My configuration file would look something like this*:
theme: "A3"
comment: "An octave below concert pitch (ie A4 440Hz)"
presets: {
A3 220Hz=220.0
}
// http://en.wikipedia.org/wiki/Guitar_tuning
theme: "Guitar Standard Tuning"
comment:"EADGBE using 12-TET tuning"
presets: {
E2=82.41
A2=110.00
D3=146.83
G3=196.00
B3=246.94
E4=329.63
}
theme: "Bass Guitar Standard Tuning"
comment: "EADG using 12-TET tuning"
presets: {
E1=41.204
A2=55.000
D3=73.416
G3=97.999
}
...which need to be extracted into some structure like this:
#class Preset
{
NSString* label;
double freq;
}
#class Theme
{
NSString* label;
NSMutableArray* presets;
}
NSMutableArray* themes;
How do I write my file using JSON? ( I would like to create a minimum of typing on the part of the user -- how succinct can I get it? Could someone give me an example for the first theme? )
And how do I parse it into the structures using https://github.com/johnezang/JSONKit?
Here's a valid JSON example based on your thoughts:
[
{
"name": "Guitar Standard Tuning",
"comment": "EADGBE using 12-TET tuning",
"presets": {
"E2": "82.41",
"A2": "110.00",
"D3": "146.83",
"G3": "196.00",
"B3": "246.94",
"E4": "329.63"
}
},
{
"name": "Bass Guitar Standard Tuning",
"comment": "EADG using 12-TET tuning",
"presets": {
"E1": "41.204",
"A1": "55.000",
"D2": "73.416",
"G2": "97.999"
}
}
]
Read a file and parse using JSONKit:
NSData* jsonData = [NSData dataWithContentsOfFile: path];
JSONDecoder* decoder = [[JSONDecoder alloc]
initWithParseOptions:JKParseOptionNone];
NSArray* json = [decoder objectWithData:jsonData];
After that, you'll have to iterate over the json variable using a for loop.
Using the parser in your question and assuming you have Simeon's string in an NSString variable. Here's how to parse it:
#import "JSONKit.h"
id parsedJSON = [myJSONString objectFromJSONString];
That will give you a hierarchy of arrays and dictionaries that you can walk to get your Preset and Theme objects. In the above case, you would get an array with two dictionaries each with a name, comment and presets key. The first two will have NSString values and the third (presets) will have a dictionary as it's value with the note name as keys and the frequencies as values (as NSString objects).