Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

url - Build Amazon Affiliate Link Swift

I would like to be able to build an Amazon-Affiliate link, when a "normal" Amazon URL is given.

I tried using this structure:

http://www.amazon.com/dp/{ASIN}/?tag={trackingId}

as suggested here.

This is how I try to create the URL:

func getAmazonAffiliateLink() -> URL? {
    if let regex = try? NSRegularExpression(pattern: "([\w-]+/)?(dp|gp/product)/(\w+/)?(\w{10})"),
       let match = regex.firstMatch(in: self, range: NSRange(self.startIndex..., in: self)),
       let asinMatchRange = Range(match.range(at: 4), in: self) {
        let asin = self[asinMatchRange]
        let partnerId = "wishlists07-21"
        let affiliateLink = "https://www.amazon.com/dp/(asin)/?tag=(partnerId)"
        return URL(string: affiliateLink)
    } else {
        return nil
    }

}

But this gives me this URL for example:

https://www.amazon.com/dp/b085sp5sxh/?tag=wishlists07-21

And as you can see for yourself, it is not working...

What am I missing here? How can I build affiliate links?

question from:https://stackoverflow.com/questions/65837717/build-amazon-affiliate-link-swift

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It looks like the initial link you're testing with is probably bad -- in other words, when I remove your wishlist tag and just try the basic Amazon link, it still fails.

But, with a valid Amazon product link, it seems to work. Here's what I did in a Playground:

extension String {
    func getAmazonAffiliateLink() -> URL? {
        if let regex = try? NSRegularExpression(pattern: "([\w-]+/)?(dp|gp/product)/(\w+/)?(\w{10})"),
           let match = regex.firstMatch(in: self, range: NSRange(self.startIndex..., in: self)),
           let asinMatchRange = Range(match.range(at: 4), in: self) {
            let asin = self[asinMatchRange]
            let partnerId = "wishlists07-21"
            let affiliateLink = "https://www.amazon.com/dp/(asin)/?tag=(partnerId)"
            return URL(string: affiliateLink)
        } else {
            return nil
        }

    }
}

"https://www.amazon.com/dp/B0863ZGP2R/ref=fs_a_ipadt2_us0".getAmazonAffiliateLink()

Which yields the result of https://www.amazon.com/dp/B0863ZGP2R/?tag=wishlists07-21 which is a working Amazon link.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...