Я пытаюсь реализовать FKFlickrPhotosCommentsAddComment, это часть Flickrkit. Как мне реализовать это с помощью кода Swift? Я выполнил авторизацию пользователя на странице входа и смог успешно войти в Flickr. Я столкнулся с другими API, которые не требуют разрешения «Запись», но для addComments говорится, что вам нужны разрешения на запись. Я знаю, что API-вызову теперь нужны параметры OAuth: Consumer Key, Consumer Secret (в кодировке SHA) и другие обязательные параметры для вызова.
Теперь я могу либо использовать метод FKFlickrPhotosCommentsAddComment, либо вручную создать API-ссылку с необходимыми параметрами. Я не понимаю, как вызвать FKFlickrPhotosCommentsAddComment в моем коде. Если бы вы могли помочь мне с этим. Если нет, то можете ли вы показать в коде, как извлечь параметры из приведенного ниже снимка экрана в моем коде, потому что эти параметры вызываются во время аутентификации и входа пользователя в систему.
Я пытаюсь выучить и перечитываю весь FlickrKit и «прыгаю к определениям» и называю «гериархией», но я не могу этого понять.
Это код метода внутри FLickrkit:
#import "FKFlickrPhotosetsCommentsAddComment.h"
@implementation FKFlickrPhotosetsCommentsAddComment
- (BOOL) needsLogin {
return YES;
}
- (BOOL) needsSigning {
return YES;
}
- (FKPermission) requiredPerms {
return 1;
}
- (NSString *) name {
return @"flickr.photosets.comments.addComment";
}
- (BOOL) isValid:(NSError **)error {
BOOL valid = YES;
NSMutableString *errorDescription = [[NSMutableString alloc] initWithString:@"You are missing required params: "];
if(!self.photoset_id) {
valid = NO;
[errorDescription appendString:@"'photoset_id', "];
}
if(!self.comment_text) {
valid = NO;
[errorDescription appendString:@"'comment_text', "];
}
if(error != NULL) {
if(!valid) {
NSDictionary *userInfo = @{NSLocalizedDescriptionKey: errorDescription};
*error = [NSError errorWithDomain:FKFlickrKitErrorDomain code:FKErrorInvalidArgs userInfo:userInfo];
}
}
return valid;
}
- (NSDictionary *) args {
NSMutableDictionary *args = [NSMutableDictionary dictionary];
if(self.photoset_id) {
[args setValue:self.photoset_id forKey:@"photoset_id"];
}
if(self.comment_text) {
[args setValue:self.comment_text forKey:@"comment_text"];
}
return [args copy];
}
- (NSString *) descriptionForError:(NSInteger)error {
switch(error) {
case FKFlickrPhotosetsCommentsAddCommentError_PhotosetNotFound:
return @"Photoset not found";
case FKFlickrPhotosetsCommentsAddCommentError_BlankComment:
return @"Blank comment";
case FKFlickrPhotosetsCommentsAddCommentError_UserIsPostingCommentsTooFast:
return @"User is posting comments too fast.";
case FKFlickrPhotosetsCommentsAddCommentError_SSLIsRequired:
return @"SSL is required";
case FKFlickrPhotosetsCommentsAddCommentError_InvalidSignature:
return @"Invalid signature";
case FKFlickrPhotosetsCommentsAddCommentError_MissingSignature:
return @"Missing signature";
case FKFlickrPhotosetsCommentsAddCommentError_LoginFailedOrInvalidAuthToken:
return @"Login failed / Invalid auth token";
case FKFlickrPhotosetsCommentsAddCommentError_UserNotLoggedInOrInsufficientPermissions:
return @"User not logged in / Insufficient permissions";
case FKFlickrPhotosetsCommentsAddCommentError_InvalidAPIKey:
return @"Invalid API Key";
case FKFlickrPhotosetsCommentsAddCommentError_ServiceCurrentlyUnavailable:
return @"Service currently unavailable";
case FKFlickrPhotosetsCommentsAddCommentError_WriteOperationFailed:
return @"Write operation failed";
case FKFlickrPhotosetsCommentsAddCommentError_FormatXXXNotFound:
return @"Format \"xxx\" not found";
case FKFlickrPhotosetsCommentsAddCommentError_MethodXXXNotFound:
return @"Method \"xxx\" not found";
case FKFlickrPhotosetsCommentsAddCommentError_InvalidSOAPEnvelope:
return @"Invalid SOAP envelope";
case FKFlickrPhotosetsCommentsAddCommentError_InvalidXMLRPCMethodCall:
return @"Invalid XML-RPC Method Call";
case FKFlickrPhotosetsCommentsAddCommentError_BadURLFound:
return @"Bad URL found";
default:
return @"Unknown error code";
}
}
@end
#import "FKFlickrAPIMethod.h"
typedef NS_ENUM(NSInteger, FKFlickrPhotosetsCommentsAddCommentError) {
FKFlickrPhotosetsCommentsAddCommentError_PhotosetNotFound = 1, /* */
FKFlickrPhotosetsCommentsAddCommentError_BlankComment = 8, /* */
FKFlickrPhotosetsCommentsAddCommentError_UserIsPostingCommentsTooFast = 9, /* The user has reached the limit for number of comments posted during a specific time period. Wait a bit and try again. */
FKFlickrPhotosetsCommentsAddCommentError_SSLIsRequired = 95, /* SSL is required to access the Flickr API. */
FKFlickrPhotosetsCommentsAddCommentError_InvalidSignature = 96, /* The passed signature was invalid. */
FKFlickrPhotosetsCommentsAddCommentError_MissingSignature = 97, /* The call required signing but no signature was sent. */
FKFlickrPhotosetsCommentsAddCommentError_LoginFailedOrInvalidAuthToken = 98, /* The login details or auth token passed were invalid. */
FKFlickrPhotosetsCommentsAddCommentError_UserNotLoggedInOrInsufficientPermissions = 99, /* The method requires user authentication but the user was not logged in, or the authenticated method call did not have the required permissions. */
FKFlickrPhotosetsCommentsAddCommentError_InvalidAPIKey = 100, /* The API key passed was not valid or has expired. */
FKFlickrPhotosetsCommentsAddCommentError_ServiceCurrentlyUnavailable = 105, /* The requested service is temporarily unavailable. */
FKFlickrPhotosetsCommentsAddCommentError_WriteOperationFailed = 106, /* The requested operation failed due to a temporary issue. */
FKFlickrPhotosetsCommentsAddCommentError_FormatXXXNotFound = 111, /* The requested response format was not found. */
FKFlickrPhotosetsCommentsAddCommentError_MethodXXXNotFound = 112, /* The requested method was not found. */
FKFlickrPhotosetsCommentsAddCommentError_InvalidSOAPEnvelope = 114, /* The SOAP envelope send in the request could not be parsed. */
FKFlickrPhotosetsCommentsAddCommentError_InvalidXMLRPCMethodCall = 115, /* The XML-RPC request document could not be parsed. */
FKFlickrPhotosetsCommentsAddCommentError_BadURLFound = 116, /* One or more arguments contained a URL that has been used for abuse on Flickr. */
};
/*
Add a comment to a photoset.
Response:
<comment id="97777-12492-72057594037942601" />
*/
@interface FKFlickrPhotosetsCommentsAddComment : NSObject <FKFlickrAPIMethod>
/* The id of the photoset to add a comment to. */
@property (nonatomic, copy) NSString *photoset_id; /* (Required) */
/* Text of the comment */
@property (nonatomic, copy) NSString *comment_text; /* (Required) */
@end
If not, this is another method for authentication, I would like to get the encoded signature in newArgs to call the addComment Flickr API which is an authenticated call:
@implementation FKURLBuilder
#pragma mark - URL Encryption
- (NSURL *) oauthURLFromBaseURL:(NSURL *)inURL method:(FKHttpMethod)method params:(NSDictionary *)params {
NSDictionary *newArgs = [self signedOAuthHTTPQueryParameters:params baseURL:inURL method:method];
NSMutableArray *queryArray = [NSMutableArray array];
for (NSString *key in newArgs) {
[queryArray addObject:[NSString stringWithFormat:@"%@=%@", key, FKEscapedURLStringPlus(newArgs[key])]];
}
NSString *newURLStringWithQuery = [NSString stringWithFormat:@"%@?%@", inURL.absoluteString, [queryArray componentsJoinedByString:@"&"]];
return [NSURL URLWithString:newURLStringWithQuery];
}
//private
- (NSDictionary *) signedOAuthHTTPQueryParameters:(NSDictionary *)params baseURL:(NSURL *)inURL method:(FKHttpMethod)method {
NSString *httpMethod = nil;
switch (method) {
case FKHttpMethodGET:
httpMethod = @"GET";
break;
case FKHttpMethodPOST:
httpMethod = @"POST";
break;
default:
break;
}
NSMutableDictionary *newArgs = params ? [params mutableCopy] : [NSMutableDictionary dictionary];
newArgs[@"oauth_nonce"] = [FKGenerateUUID() substringToIndex:8];
NSTimeInterval time = [NSDate date].timeIntervalSince1970;
newArgs[@"oauth_timestamp"] = [NSString stringWithFormat:@"%f", time];
newArgs[@"oauth_version"] = @"1.0";
newArgs[@"oauth_signature_method"] = @"HMAC-SHA1";
newArgs[@"oauth_consumer_key"] = [FlickrKit sharedFlickrKit].apiKey;
if (!params[@"oauth_token"] && [FlickrKit sharedFlickrKit].authToken) {
newArgs[@"oauth_token"] = [FlickrKit sharedFlickrKit].authToken;
}
NSString *signatureKey = nil;
if ([FlickrKit sharedFlickrKit].authSecret) {
signatureKey = [NSString stringWithFormat:@"%@&%@", [FlickrKit sharedFlickrKit].secret, [FlickrKit sharedFlickrKit].authSecret];
} else {
signatureKey = [NSString stringWithFormat:@"%@&", [FlickrKit sharedFlickrKit].secret];
}
NSMutableString *baseString = [NSMutableString string];
[baseString appendString:httpMethod];
[baseString appendString:@"&"];
[baseString appendString:FKEscapedURLStringPlus(inURL.absoluteString)];
NSArray *sortedKeys = [newArgs.allKeys sortedArrayUsingSelector:@selector(compare:)];
[baseString appendString:@"&"];
NSMutableArray *baseStrArgs = [NSMutableArray array];
for (NSString *key in sortedKeys) {
[baseStrArgs addObject:[NSString stringWithFormat:@"%@=%@", key, FKEscapedURLStringPlus(newArgs[key])]];
}
[baseString appendString:FKEscapedURLStringPlus([baseStrArgs componentsJoinedByString:@"&"])];
NSString *signature = FKOFHMACSha1Base64(signatureKey, baseString);
newArgs[@"oauth_signature"] = signature;
printf("Its getting printed");
NSLog(@"%@", signature);
return newArgs;
}