如何在iOS Swift中进行商品搜索API? [英] How to do product search api in iOS swift?

查看:75
本文介绍了如何在iOS Swift中进行商品搜索API?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用亚马逊产品广告api搜索产品.安装了awscore和alamofire拟足动物.完成了获取签名的功能,并添加了用于项目搜索的参数,以在表视图列表中获取产品图像,标题和说明.

I am using amazon product advertising api for search product. Installed awscore and alamofire cocopods. Done functionality for getting signature and added parameters for item search to get product images, title and description in table view list.

这是我尝试进行亚马逊搜索的代码:

Here is the code i tried for getting amazon search:

     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 [:]
}

已创建桥接头文件#import.

Created bridging header file #import .

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

  getSearchItem(searchKeyword: searchKeyword)

}

这是我的控制台输出:

Here is my console output:

我的问题是,点击搜索到的搜索按钮产品未列出时.我不知道发生了什么错误.谁能帮我这个忙..

My issue is when tapping search button product searched was not listing. What mistake done i don't know. Can anyone help me out of this pls..

推荐答案

根据

HTTPRequestURI组件是URI(直到但不包括查询字符串)的HTTP绝对路径组件.如果HTTPRequestURI为空,请使用正斜杠(/).

The HTTPRequestURI component is the HTTP absolute path component of the URI up to, but not including, the query string. If the HTTPRequestURI is empty, use a forward slash ( / ).

HTTPRequestURI始终为"/onca/xml";用于产品广告API. HTTPVerb是GET或POST.

HTTPRequestURI is always "/onca/xml" for Product Advertising API. HTTPVerb is either GET or POST.

尝试仅将requestURL设置为"/onca/xml";而不是完整的URL,您不应在此部分中发送完整的URL或查询字符串.

Try just setting requestURL to "/onca/xml" instead of the full URL you shouldn't be sending the full URL or the query string in this part.

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

Also you need to percent encode the values that you are sending. You are sending commas in the response group property which should be percent encoded

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)"

注意:您应该使用https而不是http

Note: You should be using https instead of http

这篇关于如何在iOS Swift中进行商品搜索API?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆