Skip to content

Instantly share code, notes, and snippets.

@alexpersian
Created October 25, 2015 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexpersian/f7d22b32121834dd25ca to your computer and use it in GitHub Desktop.
Save alexpersian/f7d22b32121834dd25ca to your computer and use it in GitHub Desktop.
//
// CameraViewController.swift
// SpotWalk
//
// Created by Alex Persian on 10/25/15.
// Copyright © 2015 alexpersian. All rights reserved.
//
import UIKit
import AVFoundation
import Alamofire
import ImageIO
class CameraViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var sendPhotoButton: UIButton!
var imagePicker: UIImagePickerController!
var capturedImage: UIImage!
var encodedImage: NSData!
var currentToken: String!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
print("INFO -> \(info)")
imagePicker.dismissViewControllerAnimated(true, completion: nil)
capturedImage = info[UIImagePickerControllerOriginalImage] as? UIImage
print(info[UIImagePickerControllerOriginalImage]?.pathExtension)
capturedImage = resizeImage(capturedImage, newWidth: 200)
imageView.image = capturedImage
encodeImage(capturedImage)
if (sendPhotoButton.hidden) {
sendPhotoButton.hidden = false
}
}
func encodeImage(image: UIImage) {
print("entering the compression zone")
if let imageData = UIImageJPEGRepresentation(image, 0.1) {
encodedImage = imageData.base64EncodedDataWithOptions([])
}
}
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage {
let scale = newWidth / image.size.width
let newHeight = image.size.height * scale
UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight))
image.drawInRect(CGRectMake(0, 0, newWidth, newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
@IBAction func takePhoto(sender: UIButton) {
imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .Camera
presentViewController(imagePicker, animated: true, completion: nil)
}
@IBAction func sendPhoto(sender: UIButton) {
// https://camfind.p.mashape.com/image_requests
let headers = [
"X-Mashape-Key": "oeuhfiGkaemshPJ5lp4Uht88b1Hip1FqV0vjsnMAFOGSVyayMs",
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
"image_request[image]": capturedImage,
"image_request[locale]": "en_US"
]
let imageParameters = [
"image": encodedImage
]
Alamofire.request(.POST, "http://104.236.5.9:3000/camtest", parameters: imageParameters)
.responseJSON { response in
debugPrint(response)
}
// Alamofire.upload(.POST, "https://camfind.p.mashape.com/image_requests", headers: headers, parameters: parameters)
// .responseJSON { response in
// debugPrint(response)
// }
Alamofire.request(.POST, "https://camfind.p.mashape.com/image_requests", headers: headers, parameters: parameters)
.responseJSON { response in
debugPrint(response) // result of response serialization
if let JSON = response.result.value {
print("<token> JSON: \(JSON["token"])")
self.currentToken = JSON["token"] as? String
Alamofire.request(.GET, "http://104.236.5.9:3000/camfind?tolken=\(self.currentToken)")
.responseJSON { response in
debugPrint(response)
if let JSON = response.result.value {
print("<barcode> JSON: \(JSON)")
}
}
}
}
}
func uploadImage(imageData: NSDate) {
let headers = [
"X-Mashape-Key": "oeuhfiGkaemshPJ5lp4Uht88b1Hip1FqV0vjsnMAFOGSVyayMs",
"Content-Type": "image/jpeg"
]
let parameters = [
"image_request[image]": "image.jpg",
"image_request[locale]": "en_US"
]
Alamofire.request(.POST, "https://camfind.p.mashape.com/image_requests", headers: headers, parameters: parameters)
.responseJSON { response in
debugPrint(response)
if let JSON = response.result.value {
print("<token> JSON: \(JSON["token"])")
}
}
}
/* --------------------------- */
// func uploadAvatar(imageData: NSData) {
// let request = urlRequestForPath("/user/upload/avatar/", parameters: nil, method: .POST) as! NSMutableURLRequest
// let boundary = generateBoundaryString()
// let boundaryStart = "--\(boundary)\r\n"
// let boundaryEnd = "--\(boundary)--\r\n"
//
// let requestBodyData = NSMutableData()
// requestBodyData.appendString(boundaryStart)
// requestBodyData.appendString("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpeg\"\r\n")
// requestBodyData.appendString("Content-Type: image/jpeg\r\n\r\n")
// requestBodyData.appendData(imageData)
// requestBodyData.appendString("\r\n")
// requestBodyData.appendString(boundaryEnd)
//
// request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// request.HTTPBody = requestBodyData
//
// UIApplication.sharedApplication().networkActivityIndicatorVisible = true
//
// return NSURLConnection.promise(request).then{ (data:NSData) -> JSON in
// UIApplication.sharedApplication().networkActivityIndicatorVisible = false
// return JSON(data: data)
// }
// }
//
// extension NSMutableData {
// func appendString(string: String) {
// let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
// appendData(data!)
// }
//
// func generateBoundaryString() -> String {
// return "Boundary-\(NSUUID().UUIDString)"
// }
// }
/* ---------------------------- */
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment