不得不说,科大讯飞是不是把iOS程序员裁了,所以没人写iOS端的SDK,使用他们的功能还能调他们的web api ,对iOS开发者来说太不友好了。
实现功能:调用科大讯飞的图片理解的web api来实现获取图片内的内容
一鉴权 获取请求url
+(NSString *)buildRequetUrl{
NSDate *currentDate = [NSDate date];//获取当前时间,日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss z"];
dateFormatter.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
//设定时间格式,这里可以设置成自己需要的格式
NSString *dateString = [dateFormatter stringFromDate:currentDate];//将时间转化成字符串
NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc] init];// 创建一个时间格式化对象
[dateFormatter2 setDateFormat:@"EEE,+dd+MMM+yyyy+HH:mm:ss+z"];
dateFormatter2.locale = [[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
dateFormatter2.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
//设定时间格式,这里可以设置成自己需要的格式
NSString *dateString2 = [dateFormatter2 stringFromDate:currentDate];//将时间转化成字符串
dateString2 = (__bridge NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
(CFStringRef) dateString2, NULL,CFSTR("!*'();:@&=$,/?%#[]"),
kCFStringEncodingUTF8);
//hmacsha256加密原始字符串
NSMutableString *builder = [[NSMutableString alloc]init];
[builder appendString:@"host: "];
[builder appendString:@"spark-api.cn-huabei-1.xf-yun.com"];
[builder appendString:@"\n"];
[builder appendString:@"date: "];
[builder appendString:dateString];
[builder appendString:@"\n"];
[builder appendString:@"GET /v2.1/image HTTP/1.1"];
NSString *sha = [self hmacSHA256WithSecret:app_secret content:builder];
NSString *authorization_origin = [NSString stringWithFormat:@"api_key=\"%@\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%@\"",api_key,sha];
NSData *authorization_origin_data = [authorization_origin dataUsingEncoding:NSUTF8StringEncoding];
NSString *authorization = [authorization_origin_data base64EncodedString];
NSString *host = @"spark-api.cn-huabei-1.xf-yun.com";
NSString *url = [NSString stringWithFormat:@"%@?authorization=%@&host=%@&date=%@",@"wss://spark-api.cn-huabei-1.xf-yun.com/v2.1/image",authorization,host,dateString2];
return url;
}
二创建请求参数
+(NSMutableDictionary *)getParmars:(NSString *)imgBaseStr{
NSMutableDictionary *body = [[NSMutableDictionary alloc] init];
NSMutableDictionary *header = [[NSMutableDictionary alloc] init];
[header setObject:app_id forKey:@"app_id"];
[header setObject:@"39769795890" forKey:@"uid"];
NSMutableDictionary *chat = [[NSMutableDictionary alloc] init];
[chat setValue:@"general" forKey:@"domain"];
[chat setValue:[NSNumber numberWithFloat:0.5] forKey:@"temperature"];
[chat setValue:[NSNumber numberWithInt:4] forKey:@"top_k"];
[chat setValue:[NSNumber numberWithInt:2048] forKey:@"max_tokens"];
NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
[parameter setValue:chat forKey:@"chat"];
NSMutableDictionary *payload = [[NSMutableDictionary alloc] init];
NSMutableDictionary *role1 = [[NSMutableDictionary alloc] init];
[role1 setValue:@"user" forKey:@"role"];
[role1 setValue:imgBaseStr forKey:@"content"];
[role1 setValue:@"image" forKey:@"content_type"];
NSMutableDictionary *role2 = [[NSMutableDictionary alloc] init];
[role2 setValue:@"user" forKey:@"role"];
[role2 setValue:@"这张图片是什么内容" forKey:@"content"];
[role2 setValue:@"text" forKey:@"content_type"];
NSArray *roles = @[role1,role2];
NSMutableDictionary *textDic = [[NSMutableDictionary alloc] init];
[textDic setValue:roles forKey:@"text"];
[payload setValue:textDic forKey:@"message"];
[body setValue:header forKey:@"header"];
[body setValue:parameter forKey:@"parameter"];
[body setValue:payload forKey:@"payload"];
return body;
}
三 使用WebSocket来进行数据请求
pod 'Starscream', '~> 4.0.0'
四 数据请求(这边我这里用的是Swift 你们可以自行改成OC或者直接用)
import Starscream
var socket: WebSocket!
let request = URLRequest(url: URL(string: buildRequetUrl())!)
socket = WebSocket(request: request)
socket.delegate = self
socket.connect()
extension KDXFViewController:WebSocketDelegate{
func didReceive(event: Starscream.WebSocketEvent, client: any Starscream.WebSocketClient) {
switch event {
case .connected(let headers):
print("WebSocket connected with headers: (headers)")
// 将字典转换为Data
if let jsonData = try? JSONSerialization.data(withJSONObject: getParmars(theImgBase64String), options: []) {
// 成功转换,jsonData是一个Data对象
// 你可以根据需要使用这个jsonData,例如保存到文件或者发送到服务器
socket.write(data: jsonData)
} else {
print("无法将字典转换为Data")
}
case .disconnected(let reason, let code):
print("WebSocket disconnected with reason: \(reason), code: \(code)")
case .text(let string):
//获取到的数据,回归主线程进行数据处理
let theJSON = JSON.init(string)
CLHHLog(message: theJSON)
DispatchQueue.main.async {
}
case .binary(let data):
print("Received binary data: \(data)")
case .error(let error):
print("WebSocket encountered an error: \(String(describing: error))")
case .ping:
break
case .pong:
break
case .viabilityChanged:
break
case .reconnectSuggested:
break
case .cancelled:
print("WebSocket cancelled")
case .peerClosed:
print("WebSocket peer closed")
}
}
}
总结:科大讯飞的webapi 有些使用WebSocket 有些是http网络请求 ,查看文档的时候注意一下。再有就是鉴权的时候是用get 还是post 这个也要仔细查看,以免浪费时间。