代码之家  ›  专栏  ›  技术社区  ›  PvDev

如何在iOS Swift中进行产品搜索API?

  •  1
  • PvDev  · 技术社区  · 6 年前
    Let SortedKeys=数组(parameters.keys)。排序(按:<) 返回已签名的参数 让allowedCharacterset=(characterset(charactersin:“!*'();:@&=+$,/?%#[]“”。倒置) 返回逃逸环 guard let url=url(字符串:url)else{ 数据=响应数据 } 让reply=data.flatmap string(数据:$0,编码:.utf8)?“”“ timestampformatter.timezone=时区(标识符:“gmt”) //让responseGroupImages:string=“图像” let operationparams:[字符串:字符串]。=[ “keywords”:搜索关键字, 让signedParams=signedParametersForParameters(参数:operationParams) 让url=“http://webservices.amazon.in/onca/xml?”+查询 让reply=send(url:url) //activityIndicator.StopAnimating()。 } GetSearchItem(搜索关键字:SearchKeyword)
    
    

    我的问题是当点击搜索按钮时,搜索的产品没有被列出。我不知道犯了什么错误。有人能帮我摆脱这个麻烦吗?

    以下是我尝试获取亚马逊搜索的代码:

         private func signedParametersForParameters(parameters: [String: String]) -> [String: String] {
        let sortedKeys = Array(parameters.keys).sorted(by: <)
    
        let query = sortedKeys.map { String(format: "%@=%@", $0, parameters[$0] ?? "") }.joined(separator: "&")
    
        let stringToSign = "GET\nwebservices.amazon.in\n/onca/xml\n\(query)"
        print("stringToSign::::\(stringToSign)")
    
        let dataToSign = stringToSign.data(using: String.Encoding.utf8)
        let signature = AWSSignatureSignerUtility.hmacSign(dataToSign, withKey: CameraViewController.kAmazonAccessSecretKey, usingAlgorithm: UInt32(kCCHmacAlgSHA256))!
    
        var signedParams = parameters;
        signedParams["Signature"] = urlEncode(signature)
        print("urlencodesignature::\(urlEncode(signature))")
    
        return signedParams
    }
    
    public func urlEncode(_ input: String) -> String {
        let allowedCharacterSet = (CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[] ").inverted)
    
        if let escapedString = input.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) {
            return escapedString
        }
    
        return ""
    }
    func send(url: String) -> String {
     //        activityIndicator.startAnimating()
        guard let url = URL(string: url) else {
            print("Error! Invalid URL!") //Do something else
     //            activityIndicator.stopAnimating()
            return ""
        }
        print("send URL: \(url)")
        let request = URLRequest(url: url)
        let semaphore = DispatchSemaphore(value: 0)
    
        var data: Data? = nil
    
        URLSession.shared.dataTask(with: request) { (responseData, _, _) -> Void in
            data = responseData
    
            print("send URL session data: \(String(describing: data))")
            let parser = XMLParser(data: data!)
            parser.delegate = self as? XMLParserDelegate
            if parser.parse() {
                print(self.results ?? "No results")
            }
            semaphore.signal()
    
            }.resume()
    
     //        activityIndicator.stopAnimating()
        semaphore.wait(timeout: .distantFuture)
    
        let reply = data.flatMap { String(data: $0, encoding: .utf8) } ?? ""
        return reply
    }
    
    public func getSearchItem(searchKeyword: String) -> [String:AnyObject]{
    
        let timestampFormatter: DateFormatter
        timestampFormatter = DateFormatter()
        timestampFormatter.timeZone = TimeZone(identifier: "GMT")
        timestampFormatter.dateFormat = "YYYY-MM-dd'T'HH:mm:ss'Z'"
        timestampFormatter.locale = Locale(identifier: "en_US_POSIX")
    
    //        let responsegroupitem: String = "ItemAttributes"
    //        let responsegroupImages:String = "Images"
    
    //        activityIndicator.startAnimating()
        let operationParams: [String: String] = [
            "Service": "AWSECommerceService",
            "Operation": "ItemSearch",
            "ResponseGroup": "Images,ItemAttributes",
            "IdType": "ASIN",
            "SearchIndex":"All",
            "Keywords": searchKeyword,
            "AWSAccessKeyId": urlEncode(CameraViewController.kAmazonAccessID),
            "AssociateTag": urlEncode(CameraViewController.kAmazonAssociateTag),
            "Timestamp": urlEncode(timestampFormatter.string(from: Date()))]
    
        let signedParams = signedParametersForParameters(parameters: operationParams)
    
    
    
        let query = signedParams.map { "\($0)=\($1)" }.joined(separator: "&")
        let url = "http://webservices.amazon.in/onca/xml?" + query
        print("querydata::::\(query)")
    
        let reply = send(url: url)
        print("reply::::\(reply)")
     //        activityIndicator.stopAnimating()
    
    
    
        return [:]
    }
    

    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    
      getSearchItem(searchKeyword: searchKeyword)
    
    }
    

    这是我的控制台输出:enter image description here

    1 回复  |  直到 6 年前
        1
  •  2
  •   Scriptable    6 年前

    根据 documentation

    此外,还需要对发送的值进行百分比编码。您正在响应组属性中发送逗号,该属性应为百分比编码

    let operationParams: [String: String] = [
        "Service": "AWSECommerceService",
        "Operation": "ItemSearch",
        "ResponseGroup": urlEncode("Images,ItemAttributes"),
        "IdType": "ASIN",
        "SearchIndex":"All",
        "Keywords": urlEncode(searchKeyword),
        "AWSAccessKeyId": urlEncode(CameraViewController.kAmazonAccessID),
        "AssociateTag": urlEncode(CameraViewController.kAmazonAssociateTag),
        "Timestamp": urlEncode(timestampFormatter.string(from: Date()))]
    

    let stringToSign = "GET\n/onca/xml\n\(query)"