ios-uploader/dcav-uploader/ViewController.swift
Alexander Munch-hansen b56924322c Changed UI a bit!
2017-08-01 14:15:59 +02:00

159 lines
6.3 KiB
Swift

//
// ViewController.swift
// dcav-uploader
//
// Created by Alexander Munch-hansen on 31/07/2017.
// Copyright © 2017 Guava. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate, URLSessionDelegate, URLSessionTaskDelegate, URLSessionDataDelegate {
@IBOutlet weak var labell: UILabel!
@IBOutlet weak var imageView: UIImageView!
var imagePickerController : UIImagePickerController!
@IBOutlet weak var dcavTextField: UITextField!
var responseString : String!
@IBOutlet weak var uploadProgressBar: UIProgressView!
@IBOutlet weak var savedPhotoImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
UserDefaults.standard.synchronize()
dcavTextField.delegate = self
labell.text = UserDefaults.standard.string(forKey: "username_preference")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onLibraryButton(_ sender: Any) {
imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = .photoLibrary
present(imagePickerController, animated: true, completion: nil)
}
@IBAction func onPhotoButton(_ sender: Any) {
imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = .camera
present(imagePickerController, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
imagePickerController.dismiss(animated: true, completion: nil)
imageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
func setTextInField(path: String) {
dcavTextField.text = path
}
@IBAction func onUploadButton(_ sender: Any) {
guard let username : String = UserDefaults.standard.string(forKey: "username_preference") else {
print("USERNAME, MOTHERFUCKER!")
// TODO create proper pop-up
return
}
guard let passphrase : String = UserDefaults.standard.string(forKey: "passphrase_preference") else {
// TODO create proper pop-up
print("PASSPHRASE, MOTHERFUCKER!")
return
}
let request = generateRequest(user: username, pass: passphrase)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(String(describing: error))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
self.responseString = String(data: data, encoding: .utf8)!
print("responseString = \(String(describing: self.responseString))")
DispatchQueue.main.async() {
self.setTextInField(path: "https://dcav.pw/\(String(describing: self.labell.text![(self.labell.text!.startIndex)]))\(String(describing: self.responseString!))")
}
}
task.resume()
}
func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}
func generateRequest(user: String, pass: String) -> URLRequest {
let params : [String : String] = [ "user": user, "pass": pass ]
let url = URL(string: UserDefaults.standard.string(forKey: "endpoint_preference")!)
let boundary = generateBoundaryString()
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData: Data = UIImagePNGRepresentation(imageView.image!)!
var body = Data()
for (key, value) in params {
body.append(Data("--\(boundary)\r\n".utf8))
body.append(Data("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n".utf8))
body.append(Data("\(value)\r\n".utf8))
}
let mimetype : String = "application/octet-stream"
body.append(Data("--\(boundary)\r\n".utf8))
body.append(Data("Content-Disposition: form-data; name=\"imagedata\"; filename=\"lolfag.png\"\r\n".utf8))
body.append(Data("Content-Type: \(mimetype)\r\n\r\n".utf8))
body.append(imageData)
body.append(Data("\r\n".utf8))
body.append(Data("--\(boundary)--\r\n".utf8))
request.httpBody = body
return request
}
@IBAction func onSaveButton(_ sender: UIButton) {
UIImageWriteToSavedPhotosAlbum(imageView.image!, nil, nil, nil);
self.savedPhotoImageView.alpha = 0
self.savedPhotoImageView.isHidden = false
UIView.animate(withDuration: 0.3, delay:0.0, options:UIViewAnimationOptions.transitionCrossDissolve, animations: {
self.savedPhotoImageView.alpha = 1
}, completion: { finished in
UIView.animate(withDuration: 0.3, delay:1, options:UIViewAnimationOptions.transitionCrossDissolve, animations: {
self.savedPhotoImageView.alpha = 0
}, completion: { finished in
self.savedPhotoImageView.isHidden = true
})
})
}
//MARK:Update progress bar
func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
uploadProgressBar.progress = Float(totalBytesSent) / Float(totalBytesExpectedToSend)
print(String(describing: uploadProgressBar.progress))
}
}