Last active
July 7, 2016 05:19
-
-
Save erkanyildiz/b84532cdcf3bc906e84d to your computer and use it in GitHub Desktop.
Google Suggestions category on NSString with language support
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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