Created
July 6, 2023 10:23
-
-
Save Teepheh-Git/c9f568380465de9ff57a0622678c813a to your computer and use it in GitHub Desktop.
swift% upload code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
func uploadImageToURL(image: UIImage, url: URL, completion: @escaping (Error?) -> Void) { | |
guard let imageData = image.jpegData(compressionQuality: 0.8) else { | |
completion(nil) | |
return | |
} | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
let boundary = generateBoundary() | |
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") | |
let body = createBody(with: imageData, boundary: boundary) | |
request.httpBody = body | |
let session = URLSession.shared | |
let task = session.dataTask(with: request) { (data, response, error) in | |
completion(error) | |
} | |
task.resume() | |
} | |
func generateBoundary() -> String { | |
return "Boundary-\(NSUUID().uuidString)" | |
} | |
func createBody(with imageData: Data, boundary: String) -> Data { | |
var body = Data() | |
// Add image data | |
body.append("--\(boundary)\r\n".data(using: .utf8)!) | |
body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n".data(using: .utf8)!) | |
body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!) | |
body.append(imageData) | |
body.append("\r\n".data(using: .utf8)!) | |
// Add any additional parameters if required | |
// body.append("--\(boundary)\r\n".data(using: .utf8)!) | |
// body.append("Content-Disposition: form-data; name=\"parameterName\"\r\n\r\n".data(using: .utf8)!) | |
// body.append("parameterValue\r\n".data(using: .utf8)!) | |
body.append("--\(boundary)--\r\n".data(using: .utf8)!) | |
return body | |
} | |
// Example usage | |
if let imageURL = URL(string: "https://fricassa-staging.itskillscenter.com/upload/") { | |
let image = UIImage(named: "yourImageName") | |
uploadImageToURL(image: image, url: imageURL) { error in | |
if let error = error { | |
print("Error uploading image: \(error.localizedDescription)") | |
} else { | |
print("Image uploaded successfully") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment