这个问题我真是摸不着头脑。我正在使用 Pocket API 允许用户从我的应用程序存档 Pocket 文章,但每当我尝试使用以下代码执行此操作时,我都会收到此错误:
Error Domain=PocketSDK Code=400 "无效请求,请参阅 API 文档" UserInfo=0xc17d3b0 {NSLocalizedDescription=无效请求,请参阅 API 文档}
代码:
NSDictionary *arguments = @{@"action": @"archive",
@"item_id": articleID};
[[PocketAPI sharedAPI] callAPIMethod:@"send" withHTTPMethod:PocketAPIHTTPMethodPOST arguments:arguments handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error) {
if (!error) {
NSLog(@"Archived article.");
}
}];
到底哪一部分是不正确的?我是不是没有向 API 发布发送方法?
编辑:我什至将其更改为
@"action"
为@"actions"
并为其提供上面的NSDictionary,它返回时没有错误,但不会影响它在Pocket网站上...
编辑2:根据Joseph Chen的回复,我将代码更改为以下内容:
// Create data to pass to the Pocket API (a JSON array of actions)
NSError *error;
NSArray *actions = @[@{@"action": @"archive",
@"item_id": articleID}];
NSData *actionsAsJSONData = [NSJSONSerialization dataWithJSONObject:actions options:kNilOptions error:&error];
NSString *actionsAsJSONString = [[NSString alloc] initWithData:actionsAsJSONData encoding:NSUTF8StringEncoding];
NSDictionary *arguments = @{@"actions": actionsAsJSONString};
[[PocketAPI sharedAPI] callAPIMethod:@"send" withHTTPMethod:PocketAPIHTTPMethodPOST arguments:arguments handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error) {
if (!error) {
NSLog(@"%@", response);
}
else {
NSLog(@"%@", error);
}
}];
返回:
action_results" = (
1
);
status = 1;
然而,当我进入网站并登录时,我“存档”的文章仍然盯着我,未存档。
根据文档,
actions
参数应该是一个JSON字典。所以你可以...
手动创建JSON字典:
NSString *jsonString = [NSString stringWithFormat:@"[{\"action\":\"archive\",\"item_id\":\"%@\"}]", articleID]; // articleID is a NSString?
NSDictionary *arguments = @{@"actions": jsonString};
使用
NSJSONSerialization
:
NSDictionary *actions = @{@"action": @"archive", @"item_id": articleID};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:actions
options:kNilOptions
error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding];
NSDictionary *arguments = @{@"actions": jsonString};
这个答案也可以作为参考。
这是(几乎)直接从我的应用程序获取的代码:
NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
NSDictionary *arguments = @{@"actions" : @[@{@"action" : @"archive",
@"item_id" : itemId,
@"time" : [NSString stringWithFormat:@"%ld", (long)timestamp]}]};
[self.pocketAPI callAPIMethod:@"send"
withHTTPMethod:PocketAPIHTTPMethodPOST
arguments:arguments
handler:^(PocketAPI *api, NSString *apiMethod, NSDictionary *response, NSError *error)
{
if (!error) {
// OK
} else {
// handle error
}
}];