How to upload an image from my iOS app to a PHP server? -


i don't know php , swift can me? have server: cs.hisarschool.k12.tr/ecs.php , code:

<?php  $firstname = $_post["firstname"]; $lastname = $_post["lastname"]; $userid = $_post["userid"]; $target_dir = "/var/www/html/uploads";  // $myfile = fopen($target_dir, "w");  if(!file_exists($target_dir))  {     echo "creating directory";     mkdir($target_dir, 0555, true); }  //$target_file = $target_dir . "/" . basename($_files["file"]["name"]);  $target_file = $target_dir . "/sc.jpg";  if (move_uploaded_file($_files["file"]["tmp_name"], $target_file)) {      echo json_encode([     "message" => "the file " . basename($_files["file"]["name"]) . " has been    uploaded.",     "status" => "ok",     "userid" => $_request["userid"]     ]);  } else {      echo json_encode([     "message" => "sorry, there error uploading file(" .   basename($_files["filename"][name])  . ").",     "status" => "error",     "userid" => $_request["userid"]     ]); }  ?> 

the swift code:

// //  viewcontroller.swift //  application // //  created kerem on 13/05/15. //  copyright (c) 2015 kerem. rights reserved. //  import uikit  class viewcontroller: uiviewcontroller, uiimagepickercontrollerdelegate, uinavigationcontrollerdelegate {      @iboutlet weak var myimageview: uiimageview!      @iboutlet weak var myactivityindicator: uiactivityindicatorview!      override func viewdidload() {         super.viewdidload()         // additional setup after loading view, typically nib.     }      override func didreceivememorywarning() {         super.didreceivememorywarning()         // dispose of resources can recreated.     }     @ibaction func uploadbuttontapped(sender : anyobject) {         myimageuploadrequest()     }     @ibaction func selectphotobuttontapped(sender : anyobject) {         var mypickercontroller = uiimagepickercontroller()         mypickercontroller.delegate = self         mypickercontroller.sourcetype = uiimagepickercontrollersourcetype.photolibrary         self.presentviewcontroller(mypickercontroller,animated:true, completion : nil)     }     func imagepickercontroller(picker: uiimagepickercontroller, didfinishpickingmediawithinfo info: [nsobject : anyobject]) {          myimageview.image = info[uiimagepickercontrolleroriginalimage] as? uiimage         self.dismissviewcontrolleranimated(true, completion: nil)     }     //buraya yaz     func myimageuploadrequest() {         println("1")         let myurl = nsurl(string : "cs.hisarschool.k12.tr/esc.php")//buraya         let request = nsmutableurlrequest(url:myurl!);         request.httpmethod = "post";         let param = [             "firstname" : "kerem",             "lastname" : "guventurk",             "userid" : "dreamkiller"         ]         let boundary = generateboundarystring()          request.setvalue("multipart/form-data; boundary=\(boundary)",forhttpheaderfield:"content-type")         let imagedata = uiimagejpegrepresentation(myimageview.image, 1)         if (imagedata == nil) {             return;         }         request.httpbody = createbodywithparameters(param, filepathkey: "file", imagedatakey: imagedata, boundary : boundary)         myactivityindicator.startanimating();          let task = nsurlsession.sharedsession().datataskwithrequest(request) {             data,response,error in             if error != nil {                 println("error=\(error)")                 return             }             println("******** response = \(response)")             let responsestring = nsstring(data:data,encoding:nsutf8stringencoding)             println("******** response data = \(responsestring!)")              var err: nserror?             var json = nsjsonserialization.jsonobjectwithdata(data, options: .mutablecontainers, error: &err) as? nsdictionary              dispatch_async(dispatch_get_main_queue(),{                 self.myactivityindicator.stopanimating()                 self.myimageview.image = nil;             });         }         task.resume()     }     //isim burada     func createbodywithparameters(parameters: [string: string]?, filepathkey: string?, imagedatakey: nsdata, boundary: string) -> nsdata {         println("2")         var body = nsmutabledata();          if parameters != nil {             (key, value) in parameters! {                 body.appendstring("–\(boundary)\r\n")                 body.appendstring("content-disposition: form-data; name=\"\(key)\"\r\n\r\n")                 body.appendstring("\(value)\r\n")             }         }          let filename = "user-profile.jpg"          let mimetype = "image/jpg"          body.appendstring("–\(boundary)\r\n")         body.appendstring("content-disposition: form-data; name=\"\(filepathkey!)\"; filename=\"\(filename)\"\r\n")         body.appendstring("content-type: \(mimetype)\r\n\r\n")         body.appenddata(imagedatakey)         body.appendstring("\r\n")          body.appendstring("–\(boundary)–\r\n")          return body     }      func generateboundarystring() -> string {         return "boundary-\(nsuuid().uuidstring)"     }  } extension nsmutabledata {     func appendstring(string: string) {         let data = string.datausingencoding(nsutf8stringencoding, allowlossyconversion: true)         appenddata(data!)     } } 

i have upload button , select button. problem is, can't upload picture website. tried different ways of selecting url, used directory of server none works... again, don't know php or swift well, wrote project of tutorial.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -