Upload Image With Parameters in Swif Library

I'chiliad trying to upload an image with parameters in Swift. When I effort this code, I can become the parameters but not the image

            uploadFileToUrl(fotiño:UIImage){     var foto =  UIImage(data: UIImageJPEGRepresentation(fotiño, 0.ii))       var asking = NSMutableURLRequest(URL:NSURL(string: URL))     request.HTTPMethod = Mail service      var bodyData = id_user=PARAMETERS&ETC       request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);     request.HTTPBody = NSData.dataWithData(UIImagePNGRepresentation(foto))     println(miraqui (request.debugDescription))     var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?>=nil     var HTTPError: NSError? = zippo     var JSONError: NSError? = nix      var dataVal: NSData? =  NSURLConnection.sendSynchronousRequest(request, returningResponse: response, fault: &HTTPError)      if ((dataVal != nil) && (HTTPError == zilch)) {         var jsonResult = NSJSONSerialization.JSONObjectWithData(dataVal!, options: NSJSONReadingOptions.MutableContainers, error: &JSONError)          if (JSONError != nil) {             println(Bad JSON)         } else {             println(Synchronous(jsonResult))         }     } else if (HTTPError != nil) {         println(Request failed)     } else {         println(No Data returned)     } }                      

edit 2:

I think that I have some problems with the path of the saved UIImage, because php tells me that the file already exist, which I retrieve is because I send it in bare

            func createRequest (#userid: String, disco: String, id_disco: String, pub: String, foto: UIImage) -> NSURLRequest {     let param = [         id_user  : userid,         name_discoteca    : disco,         id_discoteca : id_disco,         ispublic : pub] // build your dictionary withal appropriate      let boundary = generateBoundaryString()      permit url = NSURL(string: http....)     permit asking = NSMutableURLRequest(URL: url)     asking.HTTPMethod = POST     request.timeoutInterval = 60     asking.HTTPShouldHandleCookies = imitation     request.setValue(multipart/form-information; boundary=(boundary), forHTTPHeaderField: Content-Type)     var imagesaver = ImageSaver()      var prototype = foto  // However you create/get a UIImage     allow documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] equally Cord     let destinationPath = documentsPath.stringByAppendingPathComponent(VipKing.jpg)     UIImageJPEGRepresentation(image,i.0).writeToFile(destinationPath, atomically: true)       self.saveImage(foto, withFileName: asdasd22.jpg)       var path = self.documentsPathForFileName(asdasd22.jpg)       self.ViewImage.epitome = self.loadImageWithFileName(asdasd22.jpg)      //  let path1 = NSBundle.mainBundle().pathForResource(asdasd22, ofType: jpg, inDirectory: path) equally String!       **//path1 e'er crash**       println(param.debugDescription)     println(path.debugDescription)     println(boundary.debugDescription)         request.HTTPBody = createBodyWithParameters(param, filePathKey: asdasd22.jpg, paths: [path], boundary: purlieus)      println(request.debugDescription)       return request }                      

Accustomed Answer

In your annotate below, you inform us that you lot are using the $_FILES syntax to retrieve the files. That means that you want to create a multipart/form-data asking. The procedure is basically:

  1. Specify a boundary for your multipart/course-data request.

  2. Specify a Content-Type of the request that specifies that it multipart/form-data and what the boundary is.

  3. Create body of request, separating the individual components (each of the posted values every bit well as between each upload).

For more detail, see RFC 7578. Anyway, in Swift 3 and later, this might expect similar:

            /// Create asking /// /// - parameter userid:   The userid to exist passed to web service /// - parameter password: The countersign to be passed to web service /// - parameter e-mail:    The email accost to be passed to web service /// /// - returns:            The `URLRequest` that was created  func createRequest(userid: String, password: String, email: String) throws -> URLRequest {     allow parameters = [         user_id  : userid,         email    : email,         password : password]  // build your dictionary all the same appropriate      let boundary = generateBoundaryString()      allow url = URL(cord: https://instance.com/imageupload.php)!     var asking = URLRequest(url: url)     asking.httpMethod = POST     request.setValue(multipart/form-data; boundary=(boundary), forHTTPHeaderField: Content-Blazon)      allow fileURL = Package.main.url(forResource: image1, withExtension: png)!     request.httpBody = endeavor createBody(with: parameters, filePathKey: file, urls: [fileURL], boundary: boundary)      return request }  /// Create torso of the `multipart/grade-data` request /// /// - parameter parameters:   The optional dictionary containing keys and values to be passed to spider web service. /// - parameter filePathKey:  The optional field name to be used when uploading files. If you supply paths, you lot must supply filePathKey, too. /// - parameter urls:         The optional array of file URLs of the files to be uploaded. /// - parameter boundary:     The `multipart/form-data` boundary. /// /// - returns:                The `Data` of the body of the request.  private func createBody(with parameters: [Cord: Cord]?, filePathKey: Cord, urls: [URL], boundary: String) throws -> Information {     var body = Data()      parameters?.forEach { (primal, value) in         body.suspend(--(boundary)rn)         body.append(Content-Disposition: form-data; name=(key)rnrn)         torso.append((value)rn)     }      for url in urls {         allow filename = url.lastPathComponent         let data = try Information(contentsOf: url)         let mimetype = mimeType(for: filename)          trunk.append(--(purlieus)rn)         body.append(Content-Disposition: form-data; name=(filePathKey); filename=(filename)rn)         body.append(Content-Type: (mimetype)rnrn)         trunk.append(information)         body.append(rn)     }      body.append(--(purlieus)--rn)     render body }  /// Create boundary string for multipart/form-information request /// /// - returns:            The boundary string that consists of Boundary- followed past a UUID cord.  private func generateBoundaryString() -> String {     return Purlieus-(UUID().uuidString) }  /// Determine mime blazon on the footing of extension of a file. /// /// This requires `import MobileCoreServices`. /// /// - parameter path:         The path of the file for which we are going to make up one's mind the mime type. /// /// - returns:                Returns the mime type if successful. Returns `awarding/octet-stream` if unable to determine mime blazon.  private func mimeType(for path: String) -> Cord {     permit pathExtension = URL(fileURLWithPath: path).pathExtension as NSString      guard         let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil)?.takeRetainedValue(),         let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue()     else {         return application/octet-stream     }      return mimetype as String }                      

With:

            extension Data {      /// Suspend string to Data     ///     /// Rather than littering my code with calls to `data(using: .utf8)` to convert `Cord` values to `Data`, this wraps information technology in a overnice user-friendly lilliputian extension to Data. This defaults to converting using UTF-viii.     ///     /// - parameter cord:       The string to be added to the `Data`.      mutating func append(_ string: Cord, using encoding: Cord.Encoding = .utf8) {         if let data = string.data(using: encoding) {             append(data)         }     } }                      

Having all of this, you now demand to submit this request. I would advise this is washed asynchronously. For case, using URLSession, you would do something like:

            allow request: URLRequest  do {     request = attempt createRequest(userid: userid, countersign: password, email: email) } catch {     impress(error)     return }  let task = URLSession.shared.dataTask(with: request) { information, response, mistake in     baby-sit allow data = data, error == nil else {         // handle fault here         print(fault ?? Unknown error)         render     }      // parse `information` here, and so parse information technology      // note, if yous desire to update the UI, make certain to acceleration that to the main queue, due east.g.:     //     // DispatchQueue.chief.async {     //     // update your UI and model objects here     // } } task.resume()                      

For Swift 2 renditions, come across previous revision of this answer.

#Upload #image #parameters #Swift

Provide Your Ratings:

I like to dream big. My dream is to travel effectually the world. I similar to listen to music with headphones. I like to mind to music with headphones. In my free time I usually read.

What do yous think?

lanedents1968.blogspot.com

Source: https://codeinfopark.com/questions/upload-image-with-parameters-in-swift/

0 Response to "Upload Image With Parameters in Swif Library"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel