Swift 2.0
Here is a function that will sign a set of parameters for Swift. Note that this code requires the Alamofire
and AWSCore
Cocoapods to be installed. You also need to add #import <CommonCrypto/CommonCrypto.h>
to your Objective-C Bridging header otherwise kCCHmacAlgSHA256
won't be found.
private func signedParametersForParameters(parameters: [String: String]) -> [String: String] {
let sortedKeys = Array(parameters.keys).sort(<)
var components: [(String, String)] = []
for key in sortedKeys {
components += ParameterEncoding.URLEncodedInURL.queryComponents(key, parameters[key]!)
}
let query = (components.map { "\($0)=\($1)" } as [String]).joinWithSeparator("&")
let stringToSign = "GET\nwebservices.amazon.com\n/onca/xml\n\(query)"
let dataToSign = stringToSign.dataUsingEncoding(NSUTF8StringEncoding)
let signature = AWSSignatureSignerUtility.HMACSign(dataToSign, withKey: kAmazonAccessSecretKey, usingAlgorithm: UInt32(kCCHmacAlgSHA256))!
let signedParams = parameters + ["Signature": signature]
return signedParams
}
It's called like this:
let operationParams: [String: String] = ["Service": "AWSECommerceService", "Operation": "ItemLookup", "ItemId": "045242127733", "IdType": "UPC", "ResponseGroup": "Images,ItemAttributes", "SearchIndex": "All"]
let keyParams = ["AWSAccessKeyId": kAmazonAccessID, "AssociateTag": kAmazonAssociateTag, "Timestamp": timestampFormatter.stringFromDate(NSDate())]
let fullParams = operationParams + keyParams
let signedParams = signedParametersForParameters(fullParams)
Alamofire.request(.GET, "http://webservices.amazon.com/onca/xml", parameters: signedParams).responseString { (response) in
print("Success: \(response.result.isSuccess)")
print("Response String: \(response.result.value)")
}
Finally, the timestampFormatter is declared like this:
private let timestampFormatter: NSDateFormatter
init() {
timestampFormatter = NSDateFormatter()
timestampFormatter.dateFormat = AWSDateISO8601DateFormat3
timestampFormatter.timeZone = NSTimeZone(name: "GMT")
timestampFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
}
You can use/modify to suit your needs, but everything that's necessary should be there.