2016-05-04 61 views
1

我使用下面的代碼,但它不是爲我工作,並始終得到空應答,但是當URL害蟲進入瀏覽器,它會下載包含下面一個文本文件f.txt的Youtube API自動完成搜索工作不

window.google.ac.h([「Y」,[[「young thug」,0],[「youtube」,0],[「youth troye sivan」,0],[「young dolph」 ,0「,[」yo gotti「,0],[」yg「,0],[」yoga「,0],[」you should be here cole swindell「,0],[」yandere simulator「 ],[ 「年輕暴徒 最好的朋友」,0]],{ 「K」:1, 「升」: 「1」, 「q」: 「Fu65vJmwPDpRvrCvJ_hO3MqI15U」}])

@property(strong, nonatomic) NSMutableArray *ParsingArray // Put that in .h file or after @interface in your .m file 

    -(void)autocompleteSegesstions : (NSString *)searchWish{ 
//searchWish is the text from your search bar (self.searchBar.text) 


NSString *jsonString = [NSString stringWithFormat:@"http://suggestqueries.google.com/complete/search?client=youtube&ds=yt&alt=json&q=%@", searchWish]; 
    NSString *URLString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; // Encoding to identify where, for example, there are spaces in your query. 


NSLog(@"%@", URLString); 

    NSData *allVideosData = [[NSData alloc]initWithContentsOfURL:[[NSURL alloc]initWithString:URLString]]; 

NSString *str = [[NSString alloc]initWithData:allVideosData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@", str); //Now you have NSString contain JSON. 
NSString *json = nil; 
NSScanner *scanner = [NSScanner scannerWithString:str]; 
[scanner scanUpToString:@"[[" intoString:NULL]; // Scan to where the JSON begins 
[scanner scanUpToString:@"]]" intoString:&json]; 
//The idea is to identify where the "real" JSON begins and ends. 
json = [NSString stringWithFormat:@"%@%@", json, @"]]"]; 
NSLog(@"json = %@", json); 


NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding] //Push all the JSON autocomplete detail in to jsonObject array. 
                       options:0 error:NULL]; 
self.ParsingArray = [[NSMutableArray alloc]init]; //array that contains the objects. 
for (int i=0; i != [jsonObject count]; i++) { 
    for (int j=0; j != 1; j++) { 
     NSLog(@"%@", [[jsonObject objectAtIndex:i] objectAtIndex:j]); 
     [self.ParsingArray addObject:[[jsonObject objectAtIndex:i] objectAtIndex:j]]; 
     //Parse the JSON here... 

    } 

}} 

回答

1

解決此的有兩兩件事要知道這裏:

在iOS系統中9,默認情況下,HTTP://不支持。您必須安全地進行通信(使用https://)。如果必須,您可以在Info.plist中關閉此功能。 NSFileManager URL必須是磁盤上文件的路徑 - 也就是說,它們必須是文件URL。你的不是;它是一個http://網址。如果您的目標是下載一個文件然後將其複製到某個地方,請使用NSURLSession的下載任務。