2014-06-30 38 views
-1
- (IBAction)purchaseButtonTapped:(id)sender { 
    NSString *iTunesLink =[NSString stringWithFormat:@"itms://itunes.com/%@",[self urlStringForSong:[songNameLabel text]]]; 
    iTunesLink=[iTunesLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]; 
} 

-(NSString *)urlStringForSong:(NSString *)songName 
{ 
    songName=[songName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; 
    //remove mutilpe spaces by single space character 
    NSError *error = nil; 
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@" +" options:NSRegularExpressionCaseInsensitive error:&error]; 
    songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@" "]; 

    NSCharacterSet *cs=[[NSCharacterSet characterSetWithCharactersInString:@"qwertyuiopasdfghjklzxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890.-_* "] invertedSet]; 
    songName=[[songName componentsSeparatedByCharactersInSet:cs]componentsJoinedByString:@""]; 
     return songName; 
} 
+2

有什麼問題嗎?錯誤信息?期望輸出? –

+1

上面的代碼工作正常單字搜索(單詞songName),但是當我傳遞多個單詞與空格分開,iTunes打開說找不到項目,並單擊顯示在「項目未找到」文本下方的搜索按鈕,它顯示結果如預期。 –

+1

您能否顯示您正在嘗試的URL並提供錯誤? – Milo

回答

0

過去了,如果你要搜索的媒體,您可以採取的幫助這個 itunesLinkMaker

hit this url with parameters you will get response json for searched results. 
https://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/wsSearch?term=**asd**&country=US&media=music&entity=song&limit=25&genreId=&version=2&output=json&callback=jQuery18302224650508724153_1404104878083&_=1404104902716 

你可以嘗試Itunes Search APi這一個特定的字符串將指導你完成從iTunes搜索演示。

+0

上面的代碼對於單個單詞搜索(單個單詞songName)工作正常,但是當我傳遞用空格分隔的多個單詞時,iTunes打開說找不到項目並點擊「Item not found」文本下面顯示的搜索按鈕,它會按預期顯示結果。 –

0

你的問題是,你不是逃避空間。你不能只在URL中放置空格,它不會正確解析,所以你必須使用%20來逃避它。 %轉義字符,而20是空格的十六進制ASCII碼。

替換此行:

songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@" "]; 

有了:

songName=[regex stringByReplacingMatchesInString:songName options:0 range:NSMakeRange(0, [songName length]) withTemplate:@"%20"]; // Notice the %20 instead of a space 

See this link for more URL Escape Codes

+0

我曾試過這個。但這也不起作用。任何其他建議將不勝感激。 –