Search code examples
iosswiftitunes

How to add "Get it on iTunes" button


I am looking for a way to generate the "Download on iTunes" button for an app that I am making.

I just don't know how to get the URL needed to actually send a user to the iTunes store after it's tapped.

I saw this post, which talks about using the URL. I tried entering this into my app and it works just fine. However, I do not know where to generate these URLs based on song artists and title.

I understand I may just need to use Linkmaker? Is there any alternative way?

Cheers


Solution

  • I've stumbled upon the same issue early and here is how I solved this problem:

    I'm getting artist name - song name as inputs values. Then I just create an appropriate link and make a request to itunes search api and getting back a bunch of links, pick the first one and create a button.

    Note: itunes search api can't recognize spaces in an artist name and a song name, well, we should replace all spaces that occur in the string with "+" sign.

    Code snippet:

    func fetchLink(artist: String, track: String, completion: ((String?) -> ()), failure: ((NSError) -> ())?)
    {
        let artistFixedString = replaceSpacesInString(artist)
        let trackFixedString = replaceSpacesInString(track)
    
        let urlString = "https://itunes.apple.com/search?term=" + artistFixedString + "+" + trackFixedString + "&limit=1"
    
        //NOTE: here we can use NSURLSession 
        let manager = AFHTTPRequestOperationManager()
        manager.GET(urlString, parameters: nil, success: { (operation, result) -> Void in
    
            if let results = result["results"] as? [[String:AnyObject]], let track = results.first, let itunesUrl = track["trackViewUrl"] as? String
            {
                dispatch_async(MainQueue) { completion(itunesUrl) }
            }else{
                dispatch_async(MainQueue) { completion(nil) }
            }
            }) { (operation, error) -> Void in
                dispatch_async(dispatch_get_main_queue()) {
                    failure?(error)
            }
        }
    }
    
    func replaceSpacesInString(string: String, withString replacement: String = "+") -> String
    {
        return string.stringByReplacingOccurrencesOfString(" ", withString: replacement, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }