【问题标题】:Build Amazon Affiliate Link Swift构建亚马逊附属链接 Swift
【发布时间】:2021-01-22 00:29:52
【问题描述】:

当给出“正常”亚马逊URL 时,我希望能够建立一个亚马逊联盟链接。

我尝试使用这种结构:

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

按照here的建议。

这就是我尝试创建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
    }

}

但这给了我这个URL 例如:

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

正如您自己所见,它不起作用......

我在这里缺少什么?如何建立附属链接?

【问题讨论】:

    标签: swift url amazon affiliate


    【解决方案1】:

    看起来您正在测试的初始链接可能很糟糕——换句话说,当我删除您的愿望清单标签并尝试基本的亚马逊链接时,它仍然失败。

    但是,通过有效的亚马逊产品链接,它似乎可以工作。这是我在 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()
    

    产生https://www.amazon.com/dp/B0863ZGP2R/?tag=wishlists07-21 的结果,这是一个有效的亚马逊链接。

    【讨论】:

    • 你说得对……我之前在网址上打过.lowercased()。不要问我为什么 :) 没关系,它现在正在工作。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 2021-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多