2018-11-14 有道翻译代码块
2018-11-14 本文已影响8人
BoooBooo冰Booo
- (void)youdaoCloudTranslate:(NSString *)srcText srcLanguageType:(NSString *)srcType targetLanguage:(NSString *)targetType callBack:(void (^)(NSString *))callBack{
// 语言 代码
// 中文 zh-CHS
// 日文 ja
// 英文 EN
// 韩文 ko
// 法文 fr
// 俄文 ru
// 葡萄牙文 pt
// 西班牙文 es
// 越南文 vi
// 德文 de
// 阿拉伯文 ar
// 印尼文 id
///参考文档: https://ai.youdao.com/docs/doc-trans-api.s#p08
NSString *url = @"http://openapi.youdao.com/api";
NSString *appKey = @"xxxx";
NSString *key = @"xxxx";
NSString *from = srcType;
NSString *to = targetType;
NSString *query = srcText;
NSString *salt = [NSDate date].string;
NSString *str = [NSString stringWithFormat:@"%@%@%@%@",appKey,query,salt,key];
NSString *sign = str.md5String;
/// urlEncode 一下
NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *encodeContent = [query stringByAddingPercentEncodingWithAllowedCharacters: encodeUrlSet];
NSDictionary *parametersDict = @{
@"q": encodeContent,
@"appKey": appKey,
@"salt": salt,
@"from": from,
@"to":to ,
@"sign" : sign
};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager POST: url parameters: parametersDict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
// NSLog(@"************************** %@ ",responseObject[@"translation"][0]);
NSArray *textArray = responseObject[@"translation"];
if (textArray.count) {
callBack(textArray.firstObject);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
callBack(@"");
}];
}
///MARK:- 文本翻译 中文转英文
- (void)youdaoCloudTranslateChineseToEnglish:(NSString *)srcChineseText
callBack:(void(^)(NSString *targetEnglishStr))callBack{
[self youdaoCloudTranslate: srcChineseText srcLanguageType: @"zh-CHS" targetLanguage:@"EN" callBack: callBack];
}