我真的在挠头。我正在使用 Pocket API 允许用户从我的应用程序中存档 Pocket 文章,但每当我尝试使用以下代码执行此操作时,我都会收到此错误:
错误域=PocketSDK代码=400 "请求无效,请参考API文档" 用户信息=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
}
}];