Pocket API: how to modify data using callAPIMethod? - iphone

I would like to edit the data saved at Pocket using Pocket API with iOS SDK.
However, although the preparation method is tried, no response and error also come on the contrary.
As a premise
URLs can be added using other API (saveURL).
Permissions of the registered application are 'Add' and 'Modify'.
Is there any advice? Thanks.
NSError* error;
NSArray *actions = #[#{ #"action": #"delete", #"item_id": #"456853615" }];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: actions
options: kNilOptions
error: &error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding: NSUTF8StringEncoding];
// On ios simulator access_token is saved in NSUserDefaults, but on device in keychain.
// see https://github.com/Pocket/Pocket-ObjC-SDK/blob/master/SDK/PocketAPI.m#L718
NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey: #"PocketAPI.token"];
NSDictionary* argumentDictionary = #{#"consumer_key": #"<MY_CONSUMER_KEY>",
#"access_token": accessToken,
#"actions": jsonString};
[[PocketAPI sharedAPI] callAPIMethod: #"v3/send"
withHTTPMethod: PocketAPIHTTPMethodPOST
arguments: argumentDictionary
handler: ^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]); // response (null)
NSLog(#"error %#", [error localizedDescription]); // response (null)
}];

Drop the the API version, consumer_key & access_token. These are appended by the SDK.
NSError* error;
NSArray *actions = #[#{ #"action": #"delete", #"item_id": #"456853615" }];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject: actions
options: kNilOptions
error: &error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding: NSUTF8StringEncoding];
NSDictionary* argumentDictionary = #{#"actions":jsonString};
[[PocketAPI sharedAPI] callAPIMethod:#"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:argumentDictionary
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]);
NSLog(#"error %#", [error localizedDescription]);
}];

Can use the NSDictionary to argumentDictionary.
NSDictionary *argumentDictionary = #{#"actions" : #[#{#"action" : #"delete",
#"item_id" : #"456853615"}]};
[[PocketAPI sharedAPI] callAPIMethod:#"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:argumentDictionary
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error){
NSLog(#"response %#", [response description]);
NSLog(#"error %#", [error localizedDescription]);
}];

Related

unable to access JSON data in Objective-C

Ok, this is my first approach to JSONs in Objective-C (and i'm quite new to the last one too). i'm to get infos stored my json to use them in Objective-C, but when trying to load it i get null in response from NSLog(#"%#",allData); on. Can anybody please tell me what i am doing wrong? thanks in advance for your time and your patience.
oh and if needed here's the json:
http://jsonviewer.stack.hu/#http://conqui.it/ricette.json
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"recipes" ofType:#"json"];
NSError *error = nil;
NSMutableData *JSONData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&error];
NSLog(#"%#",JSONData);
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSLog(#"%#",allData);
for (NSDictionary *diction in allData) {
NSString *recipe = [diction objectForKey:#"recipe"];
[array addObject:recipe];
}
NSLog(#"%#",array);
The JSONObjectWithData method has an error parameter, of which you can avail yourself in order to diagnose the problem. For example:
NSError *error = nil;
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData
options:0
error:&error];
if (error)
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
In your comments, you suggest that you received an error about "Unescaped control character around character 414." That would suggest an error in the JSON, itself, which you might want to validate by copying into http://jsonlint.com/ and see if it reports any issues.
In response to the broader question about whether there are any Objective-C issues, there are no coding errors, per se. I can't comment on the for loop which clearly assumes that allData is an array of dictionaries to which I cannot attest without seeing the JSON. But I'll take your word for it. But, yes, the Objective-C code looks fine (albeit, a little light on checking of the return values types and error objects).
For example, if you wanted some diagnostic assert statements that you could use during development, you might do something like:
NSArray *allData = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:nil];
NSAssert(error, #"%s: JSONObjectWithData error: %#", __FUNCTION__, error);
NSLog(#"%s: array=%#", __FUNCTION__, array);
NSAssert([allData isKindOfClass:[NSArray class]], #"allData is not an array");
for (NSDictionary *diction in allData) {
NSAssert([diction isKindOfClass:[NSDictionary class]], #"%s: diction is not a dictionary (%#), __FUNCTION__, diction);
NSString *recipe = [diction objectForKey:#"recipe"];
NSAssert(recipe, #"%s: Did not find recipe key in diction (%#)", __FUNCTION__, diction);
[array addObject:recipe];
}
If any of these errors were possible runtime errors in production, you'd replace assert statements with if statements that do the necessary error handling. But hopefully it illustrates the concept.
Problem in your response is that , string values are unable to concatenate.So, I have to manually remove those tabs and new lines.
At five places you are getting error i.e:
pelate.
pasta.
pomodoro.
saporiti).
\t
- (void)viewDidLoad
{
NSString *urlStr=[NSString stringWithFormat:#"http://www.conqui.it/ricette.json"];
urlStr=[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *fileNameURL=[NSURL URLWithString:urlStr];
NSLog(#"url is %#",urlStr);
NSMutableURLRequest *filenameReq=[[NSMutableURLRequest alloc] initWithURL:fileNameURL];
NSData *responseData=[NSURLConnection sendSynchronousRequest:filenameReq returningResponse:nil error:nil];
NSString *responseString=[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
responseString=[[responseString componentsSeparatedByString:#"\n"] componentsJoinedByString:#""];
responseString=[responseString stringByReplacingOccurrencesOfString:#"\t" withString:#""];
responseData=[responseString dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"response String is %#",responseString);
[NSCharacterSet characterSetWithCharactersInString:responseString];
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: 0 error: &e];
NSLog(#"JSON Array is %# & error is %#",jsonArray,e);
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

How to autopost on twitter in iphone?

I want to auto post my static link in twitter using iphone application (without using dialog box, cancel option , send option). is it possible?
I Found this links for this:
Post in iOS 5 with TWRequest
Post in iOS 6+ with SLRequest
Use this method of Twitter Framework:
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/statuses/update.json";
NSDictionary *params = #{#"status": #"Hello, my first autopost tweet..."};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"POST"
URL:statusesShowEndpoint
parameters:params
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *dicResponse = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(#"%#",[dicResponse description]);
}
else {
NSLog(#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]);
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}

Translation using Google Api

this is the code i am using to translate from English to Vietnamese.
NSString *urlPath = [NSString stringWithFormat:#"/translate_a/t?client=t&text=%#&langpair=en|vi",txt_view.text];
NSURL *url = [[NSURL alloc] initWithScheme:#"http"
host:#"translate.google.com"
path:urlPath];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *error;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(error == nil)
{
NSString *result = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"Result : %#", result);
NSArray *arr = [api tocanizeTheString:result tocan:#","];
result = [arr objectAtIndex:0];
result = [api replaceStringwithString:result strTobeReplaced:#"[" stringReplaceWith:#""];
result = [api replaceStringwithString:result strTobeReplaced:#"\"" stringReplaceWith:#""];
txt_view.text = result; // here i get only translated data...
}
else
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
some times it give accurate result and sometimes it doesn't. please tell me whats the problem.
"My name is Taimur Mushtaq" i type this in my app, it shows correct result which is "Tên tôi là Taimur Mushtaq".
"I am a good boy" the result should be "Tôi là một chàng trai tốt". instead it is "tôi là m\u1ED9t c\u1EADu bé t\u1ED1t"

unable to parse json response from google

I am trying to parse Json response from This URL. I have used SBJsonParser, MTJSON and another parser but i am getting NULL in all three case.
apiUrlStr = #"http://maps.google.com/maps?output=dragdir&saddr=Delhi&daddr=Mumbai+to:hyderabad";
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSString *apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSUTF8StringEncoding error:nil];
SBJsonParser *json = [[[SBJsonParser alloc] init] autorelease];
NSDictionary *dictionary = [json objectWithString:apiResponse];
NSLog(#"dictionary=%#", [json objectWithString:apiResponse]);
2011-12-09 16:59:01.226 MapWithRoutes[2523:207] dictionary=(null)
Plz suggest me something
Oke if checked the url you gave with JSONlint.com and the JSON is not valid. thus can not be parsed by any library.
If you used JSONkit you can supply a NSError object with the parse call to see what went wrong:
NSError *error = nil;
NSDictionary *dictionary = [apiResponse objectFromJSONStringWithParseOptions:JKParseOptionNone error:&error];
if (!dictionary) {
NSLog(#"Error: %#", error);
}

acces JSON from server side

I have the following response from server:
{"_license":false}
And when I try to get out from there _license it displays null.I tried like this:
NSString *items = [[parser objectWithString:[request responseString] error:nil] valueForKey:#"_license"];
NSLog(#"response server%#", items);
Any idea why?And how to solve?
Try en spilt up your code, don't do every thing in one line. Then check ever variable if it contains the correct value.
NSLog(#"Server response: %#",[request responseString]);
NSError * error = nil;
NSDictionary *response = [parser objectWithString:[request responseString] error:&error]
if (!response)( {
NSLog( #"Error parsing JSON: %#", error);
return;
}
NSLog(#"Dictionary: %#", response);
NSNumber *hasValidLicense = [response objectForKey:#"_license"];
NSLog(#"Has valid license: %#", hasValidLicense);
if ([hasValidLicense boolValue]){
//Yes we have a valid license.
} else {
// No valid license.
}
replace your line with the following:
BOOL items = [[[parser objectWithString:[request responseString] error:nil] valueForKey:#"_license"] boolValue];