Skip to content

Instantly share code, notes, and snippets.

@Alicelovecode
Created August 12, 2017 15:18
Show Gist options
  • Select an option

  • Save Alicelovecode/e76c7390ab9ea8a881aeb773081bd26e to your computer and use it in GitHub Desktop.

Select an option

Save Alicelovecode/e76c7390ab9ea8a881aeb773081bd26e to your computer and use it in GitHub Desktop.
seefood4.swift
import UIKit
import VisualRecognitionV3
import SVProgressHUD
class ViewController: UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate {
let apiKey = "f394cba206eb4ff8778fce96d95801f7494fdfc8"
let version = "2017-08-12"
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var cameraButton: UIBarButtonItem!
//用cameraButton做出一個深淺,製造出可用與不可用的感覺
let imagePicker = UIImagePickerController()
var classificationResults : [String] = []
override func viewDidLoad() {
super.viewDidLoad()
imagePicker.delegate = self
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
//當cameraButton是false時,跑SVProgressHUD(緩衝畫面)
cameraButton.isEnabled = false
SVProgressHUD.show()
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage{
imageView.image = image
imagePicker.dismiss(animated: true, completion: nil)
let visualRecognition = VisualRecognition(apiKey: apiKey, version: version)
let imageData = UIImageJPEGRepresentation(image, 0.01)
let documentURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileURL = documentURL.appendingPathComponent("tempImage.jpg")
try? imageData?.write(to: fileURL, options: [])
visualRecognition.classify(imageFile: fileURL, success: { (classifiedImages)in
let classes = classifiedImages.images.first!.classifiers.first!.classes
self.classificationResults = []
for index in 1..<classes.count{
self.classificationResults.append(classes[index].classification)
}
print(self.classificationResults)
DispatchQueue.main.async {
self.cameraButton.isEnabled = true
SVProgressHUD.dismiss()
}
//用這個來,控制true or false
if self.classificationResults.contains("hotdog"){
DispatchQueue.main.async {
self.navigationItem.title = "Hotdog!"
}
}else{
DispatchQueue.main.async {
self.navigationItem.title = "Not hotdog!"
}
}
})
}else{
print("There was an error picking the image")
}
}
@IBAction func cameraTapped(_ sender: UIBarButtonItem) {
imagePicker.sourceType = .savedPhotosAlbum
imagePicker.allowsEditing = false
present(imagePicker, animated: true, completion: nil)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment