Advertisement
Guest User

Untitled

a guest
Apr 16th, 2017
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.15 KB | None | 0 0
  1. class UploadActivityVC:
  2.  
  3. UIViewController, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
  4.  
  5. @IBOutlet weak var activityImage: UIImageView!
  6. @IBOutlet weak var activityTitle: UITextField!
  7. @IBOutlet weak var activityLocation: UITextField!
  8. @IBOutlet weak var activityDescription: UITextView!
  9. @IBOutlet weak var activityCount: UILabel!
  10.  
  11. @IBOutlet weak var submitButton: UIButton!
  12.  
  13. var uuid = String()
  14. var imageSelected = false
  15.  
  16. override func viewDidLoad() {
  17. super.viewDidLoad()
  18.  
  19.  
  20. self.automaticallyAdjustsScrollViewInsets = false
  21. submitButton.isEnabled = false
  22. submitButton.alpha = 0.4
  23.  
  24. imagePicker.delegate = self
  25. imagePicker.allowsEditing = true
  26.  
  27. tap = UITapGestureRecognizer(target: self, action: #selector(self.openPhoto))
  28. tap.numberOfTapsRequired = 1
  29. self.activityImage.addGestureRecognizer(tap)
  30. self.activityImage.isUserInteractionEnabled = true
  31. }
  32.  
  33. let imagePicker = UIImagePickerController()
  34. var tap = UITapGestureRecognizer()
  35.  
  36. func openPhoto (){
  37. imagePicker.sourceType = .photoLibrary
  38. present(imagePicker, animated: true, completion: nil)
  39. }
  40.  
  41. func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  42.  
  43. activityImage.image = info[UIImagePickerControllerEditedImage] as? UIImage
  44. self.dismiss(animated: true, completion: nil)
  45.  
  46. // cast as a true to save image file in server
  47. if activityImage.image == info[UIImagePickerControllerEditedImage] as? UIImage {
  48. imageSelected = true
  49. }
  50. }
  51.  
  52.  
  53. /*func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
  54. if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
  55. //self.activityImage.image = image
  56. self.imagePicker.dismiss(animated: true, completion: nil)
  57. //saves file on server
  58. imageSelected = true
  59. }
  60. }
  61. */
  62.  
  63. func textViewDidChange(_ textView: UITextView) {
  64. let chars = textView.text.characters.count
  65. let spacing = NSCharacterSet.whitespacesAndNewlines
  66. activityCount.text = String(140 - chars)
  67. if chars > 140 {
  68. activityCount.textColor = .red
  69. submitButton.isEnabled = false
  70. submitButton.alpha = 0.4
  71. } else if textView.text.trimmingCharacters(in: spacing).isEmpty {
  72. submitButton.isEnabled = false
  73. submitButton.alpha = 0.4
  74. } else {
  75. activityCount.textColor = .black
  76. submitButton.isEnabled = true
  77. submitButton.alpha = 0.4
  78. }
  79. }
  80.  
  81. override func didReceiveMemoryWarning() {
  82. super.didReceiveMemoryWarning()
  83. // Dispose of any resources that can be recreated.
  84. }
  85.  
  86.  
  87.  
  88. func createBodyWithParams(_ parameters: [String: String]?, filePathKey: String?, imageDataKey: Data, boundary: String) -> Data {
  89.  
  90. let body = NSMutableData();
  91.  
  92. if parameters != nil {
  93. for (key, value) in parameters! {
  94. body.appendString("--(boundary)rn")
  95. body.appendString("Content-Disposition: form-data; name="(key)"rnrn")
  96. body.appendString("(value)rn")
  97. }
  98. }
  99.  
  100.  
  101. // if file is not selected, it will not upload a file to server, because we did not declare a name file
  102. var filename = ""
  103.  
  104. if imageSelected == true {
  105. filename = "post-(uuid).jpg"
  106. }
  107.  
  108.  
  109. let mimetype = "image/jpg"
  110.  
  111. body.appendString("--(boundary)rn")
  112. body.appendString("Content-Disposition: form-data; name="(filePathKey!)"; filename="(filename)"rn")
  113. body.appendString("Content-Type: (mimetype)rnrn")
  114. body.append(imageDataKey)
  115. body.appendString("rn")
  116.  
  117. body.appendString("--(boundary)--rn")
  118.  
  119. return body as Data
  120.  
  121. }
  122.  
  123.  
  124. func uploadPost() {
  125. let id = user!["id"] as! String
  126. uuid = UUID().uuidString
  127. let text = activityDescription.text as String
  128. let title = activityTitle.text //as! String
  129. //let location = activityLocation.text!
  130.  
  131. let url = URL(string: "https://cgi.soic.indiana.edu/~team7/posts.php")!
  132. //var request = URLRequest(url: url as URL!)
  133. var request = URLRequest(url: url)
  134. request.httpMethod = "POST"
  135.  
  136. let param = [
  137. "id" : id,
  138. "uuid" : uuid,
  139. "text" : text
  140. //"title" : title,
  141. //"location" : location
  142.  
  143. ]
  144.  
  145. let boundary = "Boundary-(UUID().uuidString)"
  146. request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
  147.  
  148. // if picture is selected, compress it by half
  149. var imageData = Data()
  150.  
  151. if activityImage.image != nil {
  152. imageData = UIImageJPEGRepresentation(activityImage.image!, 0.5)!
  153. }
  154.  
  155. // ... body
  156. request.httpBody = createBodyWithParams(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
  157.  
  158. URLSession.shared.dataTask(with: request) { data, response, error in
  159.  
  160. // get main queu to communicate back to user
  161. DispatchQueue.main.async(execute: {
  162.  
  163.  
  164. if error == nil {
  165.  
  166. do {
  167.  
  168. // json containes $returnArray from php
  169. let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
  170.  
  171. // declare new var to store json inf
  172. guard let parseJSON = json else {
  173. print("Error while parsing")
  174. return
  175. }
  176.  
  177. // get message from $returnArray["message"]
  178. let message = parseJSON["message"]
  179.  
  180. if message != nil {
  181. // reset UI
  182. self.activityDescription.text = ""
  183. self.activityCount.text = "140"
  184. self.activityImage.image = nil
  185. self.submitButton.isEnabled = false
  186. self.submitButton.alpha = 0.4
  187. self.imageSelected = false
  188.  
  189. //self.performSegue(withIdentifier: "postSuccess", sender: nil)
  190.  
  191. // switch to another scene
  192. //self.tabBarController?.selectedIndex = 0
  193.  
  194. let alertController = UIAlertController(title: "Success", message: "Your post has been made!", preferredStyle: UIAlertControllerStyle.alert)
  195. let okay = UIAlertAction(title: "Okay", style: .default, handler: {_ in CATransaction.setCompletionBlock({
  196. self.performSegue(withIdentifier: "postSuccess", sender: nil)})
  197. })
  198. alertController.addAction(okay)
  199. //alertController.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler:nil))
  200. self.present(alertController, animated: true, completion: nil)
  201.  
  202.  
  203.  
  204. }
  205. print(parseJSON)
  206.  
  207. } catch {
  208.  
  209. // get main queue to communicate back to user
  210. DispatchQueue.main.async(execute: {
  211. let message = "(error)"
  212. appDelegate.infoView(message: message, color: .red)
  213. })
  214. return
  215.  
  216. }
  217.  
  218. } else {
  219.  
  220. // get main queue to communicate back to user
  221. DispatchQueue.main.async(execute: {
  222. let message = error!.localizedDescription
  223. appDelegate.infoView(message: message, color: .red)
  224. })
  225. return
  226.  
  227. }
  228.  
  229.  
  230. })
  231.  
  232. }.resume()
  233.  
  234. }
  235.  
  236.  
  237.  
  238.  
  239. @IBAction func submitActivity(_ sender: AnyObject) {
  240. if !activityDescription.text!.isEmpty || activityDescription.text.characters.count <= 140{
  241. //post
  242. uploadPost()
  243. }
  244.  
  245.  
  246. }
  247.  
  248.  
  249.  
  250.  
  251. override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
  252. self.view.endEditing(false)
  253. }
  254.  
  255.  
  256.  
  257. }
  258.  
  259. /*
  260. extension NSMutableData {
  261. func appendString(string: String) {
  262. let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
  263. append(data!)
  264.  
  265. }
  266.  
  267. }
  268. */
  269.  
  270. extension String {
  271.  
  272. // cut / trimm our string
  273. func trunc(_ length: Int, trailing: String? = "...") -> String {
  274.  
  275. if self.characters.count > length {
  276. return self.substring(to: self.characters.index(self.startIndex, offsetBy: length)) + (trailing ?? "")
  277. } else {
  278. return self }
  279.  
  280. }
  281.  
  282. }
  283.  
  284. <?php
  285.  
  286.  
  287. // Step 1. Builds connection in a secure way
  288. $file = parse_ini_file("BuckIt.ini");
  289.  
  290. // store in php var inf from ini var
  291. $host = trim($file["dbhost"]);
  292. $user = trim($file["dbuser"]);
  293. $pass = trim($file["dbpass"]);
  294. $name = trim($file["dbname"]);
  295.  
  296. // includes the access.php so that we can call functions from it
  297. require ("secure/access.php");
  298. $access = new access($host, $user, $pass, $name);
  299. $access->connect();
  300.  
  301. //Step 2. Did pass data to this file
  302. //if data passed, save a post
  303.  
  304. if (!empty($_REQUEST["uuid"]) && !empty($_REQUEST["text"])) {
  305. //Step 2.1 pass POST/GET via html encryption and assign to variables
  306. $id = htmlentities($_REQUEST["id"]);
  307. $uuid = htmlentities($_REQUEST["uuid"]);
  308. $text = htmlentities($_REQUEST["text"]);
  309. //$title = htmlentities($_REQUEST["title"]);
  310. //$location = htmlentities($_REQUEST["location"]);
  311.  
  312. $folder = "posts/" . $id;
  313.  
  314. //if no posts folder
  315. if (!file_exists($folder)) {
  316. mkdir($folder, 0777, true);
  317. }
  318.  
  319.  
  320. $folder = $folder . "/" . basename($_FILES["file"]["name"]);
  321.  
  322. if (move_uploaded_file($_FILES["file"]["tmp_name"], $folder)) {
  323. $returnArray["message"] = "Post has been made with pic";
  324. $path = "https://cgi.soic.indiana.edu/~team7/posts/" . $id. "/post-" . $uuid . ".jpg";
  325. } else {
  326. $returnArray["message"] = "Post has been made without pic";
  327. $path = "";
  328. }
  329.  
  330. $access->insertPost($id, $uuid, $text, $path);
  331. $access->addPoint($id);
  332.  
  333. } else {
  334.  
  335. $id = htmlentities($_REQUEST["id"]);
  336.  
  337. $posts = $access->selectPosts($id);
  338.  
  339. if (!empty($posts)) {
  340. $returnArray["posts"] = $posts;
  341.  
  342. }
  343.  
  344.  
  345. }
  346.  
  347. $access->disconnect();
  348.  
  349. //Step 4 Feedback info
  350. echo json_encode($returnArray);
  351.  
  352. ?>
  353.  
  354. public function insertPost($id, $uuid, $text, $path) {
  355.  
  356. $sql = "INSERT INTO posts SET id=?, uuid=?, text=?,path=?";
  357. $statement = $this->conn->prepare($sql);
  358.  
  359. if (!$statement) {
  360. throw new Exception($statement->error);
  361. }
  362. $statement->bind_param("isss", $id, $uuid, $text, $path);
  363.  
  364. $returnValue = $statement->execute();
  365.  
  366. return $returnValue;
  367.  
  368. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement