Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Google Suggestions category on NSString with language support
// erkanyildiz
// 20160707-1213-UTC+09
//
// NSString+GoogleSuggestions.h
#import <Foundation/Foundation.h>
@interface NSString (GoogleSuggestions)
- (void)GoogleSuggestions:(void (^)(NSArray* suggestions, NSError* error))completion;
- (void)GoogleSuggestionsForLanguage:(NSString*)ISOLanguageCode completion:(void (^)(NSArray* suggestions, NSError* error))completion;
@end
// erkanyildiz
// 20160707-1213-UTC+09
//
// NSString+GoogleSuggestions.m
#import "NSString+GoogleSuggestions.h"
@implementation NSString (GoogleSuggestions)
- (void)GoogleSuggestions:(void (^)(NSArray* suggestions, NSError* error))completion
{
[self GoogleSuggestionsForLanguage:nil completion:completion];
}
- (void)GoogleSuggestionsForLanguage:(NSString*)ISOLanguageCode completion:(void (^)(NSArray* suggestions, NSError* error))completion
{
if(!completion) return;
NSString* APIURL = @"http://suggestqueries.google.com/complete/search?&client=chrome&hl=%@&q=%@";
if(!ISOLanguageCode || [ISOLanguageCode isEqualToString:@""])
ISOLanguageCode = @"EN";
NSString* URLString = [NSString stringWithFormat:APIURL, ISOLanguageCode.uppercaseString, self];
URLString = [URLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[NSURLSession.sharedSession dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URLString]]
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
{
if(error){ completion(nil, error); return; }
NSString* ASCIIString = [NSString.alloc initWithData:data encoding:NSASCIIStringEncoding];
NSData* UTF8Data = [ASCIIString dataUsingEncoding:NSUTF8StringEncoding];
id JSON = [NSJSONSerialization JSONObjectWithData:UTF8Data options:0 error:&error];
if(error){ completion(nil, error); return; }
NSArray* suggestions = ([JSON count] >= 2) ? JSON[1] : nil;
if (suggestions) { completion(suggestions, nil); return; }
completion(nil, [NSError errorWithDomain:@"InvalidGoogleAPIResponse" code:0 userInfo:nil]);
}] resume];
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.