MYSQL et Swift – Télécharger l'image et le file || Serait-il préférable d'utiliser Alamofire?

J'essaye de download une image, et un dossier de text (le téléchargeant en tant que données).

Jusqu'à présent, je peux download l'image seule correctement, et également download datatables du file text en le téléchargeant en tant que file .txt seul avec succès.

Maintenant, je dois download à la fois l'image et le file .txt set …

Je ne suis pas sûr de savoir comment configurer les parameters dans mon application IOS pour cela ….

Jusqu'à présent, voici comment je télécharge le file .txt (essentiellement de la même façon que je télécharge l'image mais je change le "nom de file" et "type de mime")

func createBodyWithParameters(parameters: [Ssortingng : Any]?, filePathKey: Ssortingng?,filePathKey1: Ssortingng?, imageDataKey: NSData,imageDataKey1: NSData, boundary: Ssortingng) -> NSData { let body = NSMutableData(); if parameters != nil { for (key, value) in parameters! { body.appendSsortingng("--\(boundary)\r\n") body.appendSsortingng("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.appendSsortingng("\(value)\r\n") } } let filename = "post-\(uuid).txt" let mimetype = "image/txt" body.appendSsortingng("--\(boundary)\r\n") body.appendSsortingng("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n") body.appendSsortingng("Content-Type: \(mimetype)\r\n\r\n") body.append(imageDataKey as Data) body.appendSsortingng("\r\n") body.appendSsortingng("--\(boundary)--\r\n") return body } 

Maintenant, je ne sais pas comment save à la fois l'image et le file .txt avec ce paramètre.

Ceci est cependant le rest de mon code rapide pour le download:

  let param = [ "id" : id, "uuid" : uuid, "Text" : Text, "Title" : Title ] as [Ssortingng : Any] let boundary = "Boundary-\(NSUUID().uuidSsortingng)" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") let data: Data = NSKeyedArchiver.archivedData(withRootObject: blogatsortingbutedText) var imageData = NSData() let image = CoverImage let width = CGSize(width: self.view.frame.width, height: image.size.height * (self.view.frame.width / image.size.width)) imageData = UIImageJPEGRepresentation(imageWithImage(image, scaledToSize: width), 0.5)! as NSData // ... body request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file",filePathKey1: "file1", imageDataKey: data as NSData,imageDataKey1: imageData as NSData, boundary: boundary) as Data 

Si quelqu'un a besoin de voir plus de mon code ou ne comprend pas ma question s'il vous plaît faites le moi savoir!

Merci en avance à quiconque peut aider!!

Si vous ne voulez pas vous perdre dans les mauvaises herbes de la création de requêtes complexes, une bibliothèque tierce comme Alamofire serait intelligente. C'est par le même auteur qu'AFNetworking, mais c'est une bibliothèque native de Swift.

Ainsi, une implémentation d'Alamofire pourrait ressembler à ceci:

 func performRequest(urlSsortingng: Ssortingng, id: Ssortingng, uuid: Ssortingng, text: Ssortingng, title: Ssortingng, blogAtsortingbutedText: NSAtsortingbutedSsortingng, image: UIImage) { let parameters = [ "id" : id, "uuid" : uuid, "Text" : text, "Title" : title ] let imageData = UIImageJPEGRepresentation(image, 0.5)! let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAtsortingbutedText) Alamofire.upload( multipartFormData: { multipartFormData in for (key, value) in parameters { if let data = value.data(using: .utf8) { multipartFormData.append(data, withName: key) } } multipartFormData.append(imageData, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg") multipartFormData.append(blogData, withName: "blog", fileName: "blog.archive", mimeType: "application/octet-stream") }, to: urlSsortingng, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload .validate() .responseJSON { response in switch response.result { case .success(let value): print("responseObject: \(value)") case .failure(let responseError): print("responseError: \(responseError)") } } case .failure(let encodingError): print("encodingError: \(encodingError)") } }) } 

Si vous voulez build vous-même cette request, je suggérerais quelques petites choses. Tout d'abord, puisque vous envoyez des files de types différents, vous pourriez vouloir un bon type pour encapsuler ceci:

 struct FilePayload { let fieldname: Ssortingng let filename: Ssortingng let mimetype: Ssortingng let payload: Data } 

Je ne suis pas sûr non plus de savoir quoi faire du type image/txt mime. J'utiliserais probablement application/octet-stream pour l'archive.

Quoi qu'il en soit, la construction de la requête pourrait être la suivante:

 /// Create request. /// /// - Parameters: /// - url: The URL to where the post will be sent. /// - id: The identifier of the entry /// - uuid: The UUID of the entry /// - text: The text. /// - title: The title. /// - blogAtsortingbutedText: The atsortingbuted text of the blog entry. /// - image: The `UIImage` of the image to be included. /// /// - Returns: The `URLRequest` that was created func createRequest(url: URL, id: Ssortingng, uuid: Ssortingng, text: Ssortingng, title: Ssortingng, blogAtsortingbutedText: NSAtsortingbutedSsortingng, image: UIImage) -> URLRequest { let parameters = [ "id" : id, "uuid" : uuid, "Text" : text, // I find it curious to see uppercase field names (I'd use lowercase for consistency's sake, but use whatever your PHP is looking for) "Title" : title ] let boundary = "Boundary-\(NSUUID().uuidSsortingng)" var request = URLRequest(url: url) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") // adjust if your response is not JSON // use whatever field name your PHP is looking for the image; I used `image` let imageData = UIImageJPEGRepresentation(image, 0.5)! let imagePayload = FilePayload(fieldname: "image", filename: "image.jpg", mimetype: "image/jpeg", payload: imageData) // again, use whatever field name your PHP is looking for the image; I used `blog` let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAtsortingbutedText) let blogPayload = FilePayload(fieldname: "blog", filename: "blog.archive", mimetype: "application/octet-stream", payload: blogData) request.httpBody = createBody(with: parameters, files: [imagePayload, blogPayload], boundary: boundary) return request } /// Create body of the multipart/form-data request. /// /// - Parameters: /// - parameters: The optional dictionary containing keys and values to be passed to web service. /// - files: The list of files to be included in the request. /// - boundary: The `multipart/form-data` boundary /// /// - Returns: The `Data` of the body of the request. private func createBody(with parameters: [Ssortingng: Ssortingng]?, files: [FilePayload], boundary: Ssortingng) -> Data { var body = Data() if parameters != nil { for (key, value) in parameters! { body.append("--\(boundary)\r\n") body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") body.append("\(value)\r\n") } } for file in files { body.append("--\(boundary)\r\n") body.append("Content-Disposition: form-data; name=\"\(file.fieldname)\"; filename=\"\(file.filename)\"\r\n") body.append("Content-Type: \(file.mimetype)\r\n\r\n") body.append(file.payload) body.append("\r\n") } body.append("--\(boundary)--\r\n") return body } /// Create boundary ssortingng for multipart/form-data request /// /// - returns: The boundary ssortingng that consists of "Boundary-" followed by a UUID ssortingng. private func generateBoundarySsortingng() -> Ssortingng { return "Boundary-\(NSUUID().uuidSsortingng)" } 

 extension Data { /// Append ssortingng to Data /// /// Rather than littering my code with calls to `dataUsingEncoding` to convert ssortingngs to `Data`, and then add that data to the `Data`, this wraps it in a nice convenient little `Data` extension. This converts using UTF-8. /// /// - parameter ssortingng: The ssortingng to be added to the mutable `Data`. mutating func append(_ ssortingng: Ssortingng) { if let data = ssortingng.data(using: .utf8) { append(data) } } } 

Clairement c'était le code Swift 3, donc j'ai excisé la reference NSMutableData .

Alternativement, vous pouvez faire des API de repos JSON.

  • Convertissez le contenu de votre file bloc-notes en string codée Base64.
  • Convertissez votre file image en string codée Base64.
  • Passez les deux strings codées Base64 dans les parameters de la requête.
  • Une fois que vous obtenez la string codée Base64 sur le file API dans le paramètre de la fonction.
  • Encore une fois décoder Base64 string et le stocker dans le dossier de contenu.

https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

download l'image en utilisant AFNetworking dans swift ios

Téléchargement d'une image avec AFNetworking 2.0

Remarque – Afficher l'image sur l'application iOS, vous pouvez créer une URL absolue et en utilisant la class de caching d'image, vous pouvez afficher l'image.