2016-07-29 46 views
0

到目前为止,我使用Azure数据市场“必应搜索”API在我的Objective C项目中执行图像搜索。如何在NSURLSession中传递Bing搜索Ocp-Apim-Subscription-Key?

以下是执行搜索的代码部分:

{ 
     NSData *authData; 
     NSString *authKey = @"<enter Subscription key here!>"; 
     authData = [[[NSString alloc] initWithFormat:@"%@:%@", authKey, authKey] dataUsingEncoding:NSUTF8StringEncoding]; 
     NSString *authValue = [[NSString alloc] initWithFormat:@"Basic %@", [self stringByEncodingInBase64:authData]]; 
     NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
     [config setHTTPAdditionalHeaders:@{@"Authorization": authValue}]; 

     // Timeout settings... 
     config.timeoutIntervalForRequest = 6.0; 
     config.timeoutIntervalForResource = 8.0; 

     NSMutableCharacterSet * URLQueryPartAllowedCharacterSet; 
     URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy]; 
     [URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"]; 
     NSString * escapedValue = [searchKeys stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet]; 
     NSString * urlString = [[NSString alloc] initWithFormat: 
      @"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='%@'&$top=20&$format=json", escapedValue]; 
     NSURL *JSONURL = [NSURL URLWithString:urlString]; 
     NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:JSONURL]; 
     NSURLSessionDataTask * dataTask = 
     [[NSURLSession sessionWithConfiguration:config] dataTaskWithRequest:request completionHandler:^ 
     (NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {                 
     < PROCESS YOUR DATA HERE >  
     }]; 
     [dataTask resume]; 
    } 

现在,我已经收到了微软的通知,宣布现有的Azure的数据集市的生命的尽头“Bing搜索” API 2016年12月15日发布。 当前正在通过Azure数据市场使用API​​的用户可以选择在该日期之前迁移到Microsoft Cognitive Services Search API产品。

这个新API的主要变化之一是,您创建的每个请求都必须包含Ocp-Apim-Subscription-Key HTTP标头,该标头设置为您要调用的API的订阅密钥。

我现在已经生成了密钥。 如何修改我现有的代码以通过此“Ocp-Apim-Subscription-Key”?

假设您要发布解决方案,则新密钥为qwerty12345。

回答

1

Ocp-Apim-Subscription-Key应该在Header中传递。因此,将使用NSURLSessionConfiguration及其方法setHTTPAdditionalHeaders:

NSString *authKey = @"<enter NEW key>"; 
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 
[config setHTTPAdditionalHeaders:@{@"Ocp-Apim-Subscription-Key": authKey}];