Need help to create a new Spreadsheet in objective-c - ios

Trying to use the new v4 of the sheets API to create a sheet with the following code
- (void)createSpreadsheet {
NSString *baseUrl = #"https://sheets.googleapis.com/v4/spreadsheets";
GTLObject *newSpreadsheet = [[GTLObject alloc] init];
NSArray *keys = [NSArray arrayWithObjects:#"title", nil];
NSArray *objects = [NSArray arrayWithObjects:#"APIv4 Test", nil];
NSMutableDictionary *jsonDict = [NSMutableDictionary dictionaryWithObjects:objects forKeys:keys];
[newSpreadsheet setJSONValue:jsonDict forKey:#"properties"];
//[newSpreadsheet setJSON:jsonDict];
[self.service fetchObjectByInsertingObject:newSpreadsheet forURL:[NSURL URLWithString:baseUrl]
delegate:self
didFinishSelector:#selector(displaySheetIDWithServiceTicket:finishedWithObject:error:)];
}
The error I get is:
The operation couldn't be completed.
(Client project not found. Please pass a valid project.)
I guess there is something wrong with my JSON representation? Or am I using the wrong method call to create a new spreadsheet?
If I try and use fetchObjectByUpdatingObject I get a 404 not found error which makes sense since it doesn't exist yet.
I know I can do it with the Drive API but would prefer to use the new v4 function.

Enable the Sheets API in your Developer console

Related

Sending JSON object ios

I'm new to iOS and looking for a little help. I am connecting to my socket server but having trouble emitting.
Heres how to emit:
if (self.socketIsConnected)
{
[self.socket emit:(NSString HERE) args:#[(NSArray HERE)]];
}
Heres what I tried:
if (self.socketIsConnected)
{
NSDictionary *deviceDic = #{#"username": #"drew", #"chatHash":#"FJHE8"};
[self.socket emit:#"adduser" args:#[[NSString stringWithFormat: #"%#", deviceDic]]];
}
The "args" param asks for a NSArray, but I need to send a JSON object that looks like this:
{"username": "drew", "chatHash":"FJHE8"}
How can I create this? And how do I put this object in the NSArray.
Update:
I tried this now
NSArray *keys = [NSArray arrayWithObjects:#"username", #"chatHash", nil];
NSArray *objects = [NSArray arrayWithObjects:#"drew", #"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
[self.socket emit:#"adduser" args:dictionary];
and I looked on the server. It crashes my server with a throw exception. and the only data it receives is:
username
It appears that you're using SIOSocket. The documentation isn't very clear but looking at the source for the emit function (https://github.com/MegaBits/SIOSocket/blob/master/SocketIO/Source/SIOSocket.m), all you need to do is pass an NSArray with the first parameter being an NSDictionary. The dictionary will be serialized as a JSON object by the framework.
You can have multiple arguments in the emit call. The type of each parameter in argument depends on the types of objects in the array you pass. If you pass a dictionary, it'll convert it to a JSON object, an array to an array, numbers as numbers, strings as strings.
You can use
NSDictionary *subArgs = #{#"state" : #true};
[self.socket emit:#"adduser" args:#[subArgs]];
This will solve the problem.

Core Data error with string symbols register

I faced with strange Core Data behavior.
When I check my database with SQLIte Database Viewer I see "STRING" value. But when I read this value I get "String".
Code I use is reported below:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
//which entity (or table) to select data
[request setEntity: [[mdl entitiesByName] objectForKey:#"KeyName"]];
NSError *error = nil;
NSArray *dataArray = [cntx executeFetchRequest:request error:&error];
How can it be? How data can be transformed during reading?
Actually my application is Osirix DICOM viewer plugin.
Fortunately I get answer on Osirix Development Group conference
http://tech.groups.yahoo.com/group/osirix-dev/message/3469
I use valueForKey method to get data from NSArray *dataArray array
But the proper method here is primitiveValueForKey
valueForKey work with Osirix 4.x
Osirix 5.x has property "Display patient names and descriptions in Capitalized Words".
If this property is ON valueForKey doesn't work.
We should use primitiveValueForKey is this case.
NSArray *dataArray = [cntx executeFetchRequest:request error:&error];
for( i ... )
{
DicomStudy *study = [dataArray objectAtIndex: i];
NSString *myValue = [study primitiveValueForKey:myKey];
}

JSON not working as expected on iOS

I'm currently trying to parse this JSON
[{"id":"1","dish_name":"Pasta & ketchup","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKetchup\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"},{"id":"2","dish_name":"Pasta & Kødsovs","category":"main","rating":"5","rating_count":null,"author":"Me","ingredients":"Pasta\nKødsovs\nWater","description":"Very good for students\nCheap too!","picture":null,"protein":"7","fat":"11","carbs":"12","calories":"244","developer_lock":"1"}]
But it fails and crashes with this code
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSError *error = NULL;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
recipes = [[NSArray alloc] initWithArray:[json objectForKey:#"dish_name"]];
[uit reloadData];
}
Do someone have any clue, why it crashes with error -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8077240
?
Thanks in advance.
The error message beginning with [__NSCFArray objectForKey:] means that you have an NSArray (the root object of the JSON is an array - notice the opening and closing square brackets) and you're trying to treat it as a dictionary. All in all,
recipes = [[NSArray alloc] initWithObject:[json objectForKey:#"dish_name"]];
should be
recipes = [[NSArray alloc] initWithObject:[[json objectAtIndex:0] objectForKey:#"dish_name"]];
Note that there are two objects in the array, so you might want to use [json objectAtIndex:1] as well.
Edit: if you have a dynamic number of recipes, you can do this:
recipes = [[NSMutableArray alloc] init];
for (NSDictionary *dict in json) {
[recipes addObject:[dict objectForKey:#"dish_name"]];
}
If your json NSDictionary were a real & valid NSDictionary object, your call to this:
[json objectForKey:#"dish_name"]
should return exactly this:
"Pasta & ketchup"
Which is definitely not an array. It's a NSString object.
Which would be why the call to "initWithArray" is bombing.

How to use JSON request from YQL stock data?

I just used this answer to set up a data request from Yahoo Finance. If you take a look at the post, you'll see it returns a dictionary of data (in this case, bids) and keys (symbols). Just to test it, I used this code, but it continues to crash:
NSArray *tickerArray = [[NSArray alloc] initWithObjects:#"AAPL", nil];
NSDictionary *quotes = [self fetchQuotesFor:tickerArray];
NSLog(#"%#",[quotes valueForKey:#"AAPL"]);
Can you point out what I'm doing wrong? I need to get a string containing the data for the symbols I ask for.
PLEASE NOTE:My code is using the code that this post was based on, i.e. this.
The code you liked to is making the wrong assumption about the shape of the JSON data coming back from the API and you're getting a standard KVC error. reason: '[<__NSCFString 0x7685930> valueForUndefinedKey:]: this class is not key value coding-compliant for the key BidRealtime.'
With some debugging I got it working...
Based on your input array and by slightly modifying the function linked too, you need to access the quote like so:
#define QUOTE_QUERY_PREFIX #"http://query.yahooapis.com/v1/public/yql?q=select%20symbol%2C%20BidRealtime%20from%20yahoo.finance.quotes%20where%20symbol%20in%20("
#define QUOTE_QUERY_SUFFIX #")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback="
+ (NSDictionary *)fetchQuotesFor:(NSArray *)tickers {
NSMutableDictionary *quotes;
if (tickers && [tickers count] > 0) {
NSMutableString *query = [[NSMutableString alloc] init];
[query appendString:QUOTE_QUERY_PREFIX];
for (int i = 0; i < [tickers count]; i++) {
NSString *ticker = [tickers objectAtIndex:i];
[query appendFormat:#"%%22%#%%22", ticker];
if (i != [tickers count] - 1) [query appendString:#"%2C"];
}
[query appendString:QUOTE_QUERY_SUFFIX];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil] : nil;
NSDictionary *quoteEntry = [results valueForKeyPath:#"query.results.quote"];
return quoteEntry;
}
return quotes;
}
You'll notice the difference between the code I've posted here and the function you linked too is the final parsing of quoteEntry. I worked out what it was doing with some breakpoints, specifically on all exceptions that lead me to the exact line.
All you have to do is initialize the NSMutableDictionary!
NSMutableDictionary *quotes = [[NSMutableDictionary alloc] init];
BTW the guy above is totally NOT making use of the quotes dict. straight up returning the quoteEntry. Skipping one step. :)

Sorting the Key/Values stored in NSArray

I have a
NSDictionary* dict = [[NSDictionary alloc]initWithObjectsAndKeys::arrayOne,#"Plants",arrayTwo,#"Animals"),arrayThree,#"Birds",nil];`
self.displayArray =[[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
Everything works fine, I am able to see all the key value/pair in the table but they are in sorted order. i.e Animals,Birds,Plants.
But I want to display as Plants,Animals,Birds.
Can anyone tell me how to sort the array in my customized order?
I have googled and found that we can use NSSortDescriptor for sorting. But I am not very clear with that. Can anyone help me ?
As your ordering doesnt follow any natural order, a simple solution could be to keep track of the order with another array
NSArray *array1 = [NSArray arrayWithObjects:#"rose",#"orchid",#"sunflower",nil];
NSArray *array2 = [NSArray arrayWithObjects:#"dog", #"cat",#"ogre",#"wookie", nil];
NSArray *array3 = [NSArray arrayWithObjects:#"parrot",#"canary bird",#"tweety",#"bibo",nil];
NSArray *keys = [NSArray arrayWithObjects:#"Plants",#"Animals",#"Birds", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:
array1,[keys objectAtIndex:0],
array2,[keys objectAtIndex:1],
array3,[keys objectAtIndex:2],
nil];
for (NSString *key in keys) {
NSLog(#"%# %#", key, [dict objectForKey:key]);
}
Matt shows in his fantastic blog, how to create a ordered dictionary, that essentially uses another array to keep the order just as I showed here: OrderedDictionary: Subclassing a Cocoa class cluster
You're on the right track, Cyril.
Here is some Apple documentation on "Creating and using Sort Descriptors"
Basically you need to subclass NSSortDescriptor and in your subclass, implement your own "compare:" method (you can actually name it anything you want; it needs to return a "NSComparisonResult") that somehow logically returns "Plants" before "Animals".

Resources