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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…