Created
March 22, 2018 13:39
-
-
Save pj4533/fef6e6007672e5bd84f52af46c2d937e to your computer and use it in GitHub Desktop.
Example reverse google image search to discogs lookup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func searchUsingImage(image: UIImage) { | |
if let imageData: NSData = UIImageJPEGRepresentation(image, 0.7) { | |
SVProgressHUD.showWithStatus("Searching...") | |
Alamofire.upload( | |
.POST, | |
"https://images.google.com/searchbyimage/upload", | |
multipartFormData: { multipartFormData in | |
multipartFormData.appendBodyPart(data: imageData, name: "encoded_image") | |
}, | |
encodingCompletion: { encodingResult in | |
switch encodingResult { | |
case .Success(let upload, _, _): | |
upload.responseString(completionHandler: { response -> Void in | |
if let htmlString = response.result.value { | |
let components = htmlString.componentsSeparatedByString("tbs%3Dsbi:") | |
if components.count >= 2 { | |
let components2 = components[1].componentsSeparatedByString("\"") | |
let imageFingerprint = components2[0] | |
let headers = [ | |
"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4" | |
] | |
Alamofire.request(.GET, "https://www.google.com/search?tbs=sbi:\(imageFingerprint)", headers: headers) | |
.responseString { response in | |
if let searchHTMLString = response.result.value { | |
let components = searchHTMLString.componentsSeparatedByString("/search?q=") | |
if components.count >= 2 { | |
let components2 = components[1].componentsSeparatedByString("&") | |
let keywords = components2[0].stringByReplacingOccurrencesOfString("+", withString: " ") | |
self.title = keywords | |
Alamofire.request(.GET, "https://api.discogs.com/database/search", parameters: [ | |
"q": keywords, | |
"type": "release", | |
"key": "<discogs key>", | |
"secret": "<discogs secret>" | |
]) | |
.responseJSON { response in | |
SVProgressHUD.dismiss() | |
if let JSON = response.result.value { | |
if let releasesArray = JSON["results"] as? NSArray { | |
for release in releasesArray { | |
self.releases.append(release) | |
} | |
self.tableView.reloadData() | |
} | |
} | |
} | |
} else { | |
SVProgressHUD.showErrorWithStatus("None found...") | |
} | |
} | |
} | |
} else { | |
SVProgressHUD.showErrorWithStatus("Fingerprinting failed, try again.") | |
} | |
} | |
}) | |
case .Failure(let encodingError): | |
print(encodingError) | |
} | |
} | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment