gpt4 book ai didi

ios - 如何在 iOS swift 中做产品搜索 api?

转载 作者:搜寻专家 更新时间:2023-11-01 07:01:39 24 4
gpt4 key购买 nike

我正在使用亚马逊产品广告 API 搜索产品。安装 awscore 和 alamofire cocopods。完成了获取签名的功能,并为项目搜索添加了参数,以在表格 View 列表中获取产品图片、标题和描述。

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

     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。

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {

getSearchItem(searchKeyword: searchKeyword)

}

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

我的问题是点击搜索按钮时搜索的产品未列出。我不知道犯了什么错误。谁能帮我解决这个问题..

最佳答案

根据documentation :

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 is always "/onca/xml" for Product Advertising API. HTTPVerb is either GET or POST.

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

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

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

关于ios - 如何在 iOS swift 中做产品搜索 api?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50868971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com