Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class UploadActivityVC:
- UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
- @IBOutlet weak var activityImage: UIImageView!
- @IBOutlet weak var activityTitle: UITextField!
- @IBOutlet weak var activityLocation: UITextField!
- @IBOutlet weak var activityDescription: UITextView!
- @IBOutlet weak var activityCount: UILabel!
- @IBOutlet weak var submitButton: UIButton!
- var uuid = String()
- var imageSelected = false
- override func viewDidLoad() {
- super.viewDidLoad()
- self.automaticallyAdjustsScrollViewInsets = false
- submitButton.isEnabled = false
- submitButton.alpha = 0.4
- imagePicker.delegate = self
- imagePicker.allowsEditing = true
- tap = UITapGestureRecognizer(target: self, action: #selector(self.openPhoto))
- tap.numberOfTapsRequired = 1
- self.activityImage.addGestureRecognizer(tap)
- self.activityImage.isUserInteractionEnabled = true
- }
- let imagePicker = UIImagePickerController()
- var tap = UITapGestureRecognizer()
- func openPhoto (){
- imagePicker.sourceType = .photoLibrary
- present(imagePicker, animated: true, completion: nil)
- }
- func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
- activityImage.image = info[UIImagePickerControllerEditedImage] as? UIImage
- self.dismiss(animated: true, completion: nil)
- // cast as a true to save image file in server
- if activityImage.image == info[UIImagePickerControllerEditedImage] as? UIImage {
- imageSelected = true
- }
- }
- /*func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
- if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
- //self.activityImage.image = image
- self.imagePicker.dismiss(animated: true, completion: nil)
- //saves file on server
- imageSelected = true
- }
- }
- */
- func textViewDidChange(_ textView: UITextView) {
- let chars = textView.text.characters.count
- let spacing = NSCharacterSet.whitespacesAndNewlines
- activityCount.text = String(140 - chars)
- if chars > 140 {
- activityCount.textColor = .red
- submitButton.isEnabled = false
- submitButton.alpha = 0.4
- } else if textView.text.trimmingCharacters(in: spacing).isEmpty {
- submitButton.isEnabled = false
- submitButton.alpha = 0.4
- } else {
- activityCount.textColor = .black
- submitButton.isEnabled = true
- submitButton.alpha = 0.4
- }
- }
- override func didReceiveMemoryWarning() {
- super.didReceiveMemoryWarning()
- // Dispose of any resources that can be recreated.
- }
- func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
- let body = NSMutableData();
- if parameters != nil {
- for (key, value) in parameters! {
- body.appendString("--(boundary)rn")
- body.appendString("Content-Disposition: form-data; name="(key)"rnrn")
- body.appendString("(value)rn")
- }
- }
- // if file is not selected, it will not upload a file to server, because we did not declare a name file
- var filename = ""
- if imageSelected == true {
- filename = "post-(uuid).jpg"
- }
- let mimetype = "image/jpg"
- body.appendString("--(boundary)rn")
- body.appendString("Content-Disposition: form-data; name="(filePathKey!)"; filename="(filename)"rn")
- body.appendString("Content-Type: (mimetype)rnrn")
- body.append(imageDataKey)
- body.appendString("rn")
- body.appendString("--(boundary)--rn")
- return body as Data
- }
- func uploadPost() {
- let id = user!["id"] as! String
- uuid = UUID().uuidString
- let text = activityDescription.text as String
- let title = activityTitle.text //as! String
- //let location = activityLocation.text!
- let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
- //var request = URLRequest(url: url as URL!)
- var request = URLRequest(url: url)
- request.httpMethod = "POST"
- let param = [
- "id" : id,
- "uuid" : uuid,
- "text" : text
- //"title" : title,
- //"location" : location
- ]
- let boundary = "Boundary-(UUID().uuidString)"
- request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
- // if picture is selected, compress it by half
- var imageData = Data()
- if activityImage.image != nil {
- imageData = UIImageJPEGRepresentation(activityImage.image!, 0.5)!
- }
- // ... body
- request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
- URLSession.shared.dataTask(with: request) { data, response, error in
- // get main queu to communicate back to user
- DispatchQueue.main.async(execute: {
- if error == nil {
- do {
- // json containes $returnArray from php
- let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
- // declare new var to store json inf
- guard let parseJSON = json else {
- print("Error while parsing")
- return
- }
- // get message from $returnArray["message"]
- let message = parseJSON["message"]
- if message != nil {
- // reset UI
- self.activityDescription.text = ""
- self.activityCount.text = "140"
- self.activityImage.image = nil
- self.submitButton.isEnabled = false
- self.submitButton.alpha = 0.4
- self.imageSelected = false
- //self.performSegue(withIdentifier: "postSuccess", sender: nil)
- // switch to another scene
- //self.tabBarController?.selectedIndex = 0
- let alertController = UIAlertController(title: "Success", message: "Your post has been made!", preferredStyle: UIAlertControllerStyle.alert)
- let okay = UIAlertAction(title: "Okay", style: .default, handler: {_ in CATransaction.setCompletionBlock({
- self.performSegue(withIdentifier: "postSuccess", sender: nil)})
- })
- alertController.addAction(okay)
- //alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil))
- self.present(alertController, animated: true, completion: nil)
- }
- print(parseJSON)
- } catch {
- // get main queue to communicate back to user
- DispatchQueue.main.async(execute: {
- let message = "(error)"
- appDelegate.infoView(message: message, color: .red)
- })
- return
- }
- } else {
- // get main queue to communicate back to user
- DispatchQueue.main.async(execute: {
- let message = error!.localizedDescription
- appDelegate.infoView(message: message, color: .red)
- })
- return
- }
- })
- }.resume()
- }
- @IBAction func submitActivity(_ sender: AnyObject) {
- if !activityDescription.text!.isEmpty || activityDescription.text.characters.count <= 140{
- //post
- uploadPost()
- }
- }
- override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
- self.view.endEditing(false)
- }
- }
- /*
- extension NSMutableData {
- func appendString(string: String) {
- let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
- append(data!)
- }
- }
- */
- extension String {
- // cut / trimm our string
- func trunc(_ length: Int, trailing: String? = "...") -> String {
- if self.characters.count > length {
- return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + (trailing ?? "")
- } else {
- return self }
- }
- }
- <?php
- // Step 1. Builds connection in a secure way
- $file = parse_ini_file("BuckIt.ini");
- // store in php var inf from ini var
- $host = trim($file["dbhost"]);
- $user = trim($file["dbuser"]);
- $pass = trim($file["dbpass"]);
- $name = trim($file["dbname"]);
- // includes the access.php so that we can call functions from it
- require ("secure/access.php");
- $access = new access($host, $user, $pass, $name);
- $access->connect();
- //Step 2. Did pass data to this file
- //if data passed, save a post
- if (!empty($_REQUEST["uuid"]) && !empty($_REQUEST["text"])) {
- //Step 2.1 pass POST/GET via html encryption and assign to variables
- $id = htmlentities($_REQUEST["id"]);
- $uuid = htmlentities($_REQUEST["uuid"]);
- $text = htmlentities($_REQUEST["text"]);
- //$title = htmlentities($_REQUEST["title"]);
- //$location = htmlentities($_REQUEST["location"]);
- $folder = "posts/" . $id;
- //if no posts folder
- if (!file_exists($folder)) {
- mkdir($folder, 0777, true);
- }
- $folder = $folder . "/" . basename($_FILES["file"]["name"]);
- if (move_uploaded_file($_FILES["file"]["tmp_name"], $folder)) {
- $returnArray["message"] = "Post has been made with pic";
- $path = "https://cgi.soic.indiana.edu/~team7/posts/" . $id. "/post-" . $uuid . ".jpg";
- } else {
- $returnArray["message"] = "Post has been made without pic";
- $path = "";
- }
- $access->insertPost($id, $uuid, $text, $path);
- $access->addPoint($id);
- } else {
- $id = htmlentities($_REQUEST["id"]);
- $posts = $access->selectPosts($id);
- if (!empty($posts)) {
- $returnArray["posts"] = $posts;
- }
- }
- $access->disconnect();
- //Step 4 Feedback info
- echo json_encode($returnArray);
- ?>
- public function insertPost($id, $uuid, $text, $path) {
- $sql = "INSERT INTO posts SET id=?, uuid=?, text=?,path=?";
- $statement = $this->conn->prepare($sql);
- if (!$statement) {
- throw new Exception($statement->error);
- }
- $statement->bind_param("isss", $id, $uuid, $text, $path);
- $returnValue = $statement->execute();
- return $returnValue;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement