我想運行這段代碼,但它不工作。我試過其他解決方案列出了相同的問題,但到目前爲止沒有任何工作。我試着在dispatch_async中放入一個nslog,但它甚至沒有被調用。Dispatch_async沒有被調用,nslog也不是那麼好
- (void)viewDidLoad {
[super viewDidLoad];
self.keyboard = [[[NSBundle mainBundle] loadNibNamed:@"Keyboard" owner:nil options:nil] objectAtIndex:0];
[self addGesturesToKeyboard];
self.inputView = self.keyboard;
}
- (void)addGesturesToKeyboard {
[self.keyboard.searchKey addTarget:self action:@selector(pressSearchKey) forControlEvents:UIControlEventTouchUpInside];
}
- (void)pressSearchKey {
NSInteger numberOfResults = 3;
NSString *searchString = self.keyboard.textField.text;
NSString *encodedSearchString = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalSearchString = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?term=%@&entity=song&limit=%ld",searchString,numberOfResults];
NSURL *searchURL = [NSURL URLWithString:finalSearchString];
dispatch_queue_t iTunesQueryQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, kNilOptions);
dispatch_async(iTunesQueryQueue, ^{
self.keyboard.firstLabel.text = @"hi";
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:searchURL];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.results = [NSMutableArray array];
NSArray *resultsArray = [JSON objectForKey:@"results"];
for (NSDictionary *bpDictionary in resultsArray) {
// self.keyboard.firstLabel.text = [bpDictionary objectForKey:@"trackName"];
}
}
});
[self.keyboard.view1 setHidden:YES];
[self.keyboard.view2 setHidden:NO];
}
修訂
dispatch_async(iTunesQueryQueue, ^{
NSError *error = nil;
NSData *data = [[NSData alloc] initWithContentsOfURL:searchURL options:NSDataReadingUncached error:&error];
if (data && !error) {
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *array = [JSON objectForKey:@"results"];
dispatch_async(dispatch_get_main_queue(), ^{
self.keyboard.firstLabel.text = [array objectAtIndex:0];
});
}
});
你把這段代碼放在哪裏?如果你在這個代碼之前加上一個'NSLog',它是否打印出任何東西? – Garrett 2014-11-09 04:01:49
沒有足夠的信息來回答您的問題,但它看起來像'dispatch_async'永遠不會到達。 – 2014-11-09 04:03:35
此代碼在' - (void)pressSearchKey)'方法中,該方法從另一個方法調用'[self.keyboard.searchKey addTarget:self action:@selector(pressSearchKey)forControlEvents:UIControlEventTouchUpInside];'in' - ( void)addGesturesToKeyboard'並在'viewDidLoad'中調用。當我在該代碼之前放置一個NSLog時,NSLog工作。 – abc123abc 2014-11-09 04:04:31