感謝。在閱讀了微軟的一些文檔後,我能夠解決這個問題。這是需要的代碼:
// Method required to encode data...
-(NSString *)stringByEncodingInBase64:(NSData *)data
{
NSUInteger length = [data length];
NSMutableData *mutableData = [[NSMutableData alloc] initWithLength:((length + 2)/3) * 4];
uint8_t *input = (uint8_t *)[data bytes];
uint8_t *output = (uint8_t *)[mutableData mutableBytes];
for (NSUInteger i = 0; i < length; i += 3)
{
NSUInteger value = 0;
for (NSUInteger j = i; j < (i + 3); j++)
{
value <<= 8;
if (j < length)
{
value |= (0xFF & input[j]);
}
}
static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/";
NSUInteger idx = (i/3) * 4;
output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '=';
output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '=';
}
return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
以下是代碼來獲取搜索結果:
NSData *authData;
NSString *authKey = @"<ENTER Windows Azure Marketplace Account KEY HERE>";
NSLog (@"authkey:%@",authKey);
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}];
NSMutableCharacterSet * URLQueryPartAllowedCharacterSet;
URLQueryPartAllowedCharacterSet = [[NSCharacterSet URLQueryAllowedCharacterSet] mutableCopy];
[URLQueryPartAllowedCharacterSet removeCharactersInString:@"&+=?"]; // %26, %3D, %3F
NSString * escapedValue = [<ENTER SEARCH CRITERIA HERE> stringByAddingPercentEncodingWithAllowedCharacters:URLQueryPartAllowedCharacterSet];
NSString * urlString = [[NSString alloc] initWithFormat:@"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query='%@'&$top=50&$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) {
if(data == nil){
// Process failure here.
}
NSDictionary *resultadoCompleto = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:nil];
// PROCESS BING! RESULTS HERE...
}];
[dataTask resume];
resultadoCompleto顯示了完整的結果!