Created
December 25, 2022 15:45
-
-
Save drosenstark/710759c064bb064efe650241dbbac096 to your computer and use it in GitHub Desktop.
MultipartRequest for Uploading images and forms to a server using URLSession in Swift
This file contains 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
/// MultipartRequest by Dan Rosenstark | |
/// Thanks to tinyurl.com/2qpbyh7v: this code is just a remix | |
/// | |
/// Steps to use | |
/// 1. init | |
/// 2. add form fields (if any) | |
/// 3. add file data (if any) | |
/// 4. grab the urlRequest and use it | |
struct MultipartRequest { | |
private let boundary = "Boundary-\(UUID().uuidString)" | |
private let url: URL | |
private var formFields = [String]() | |
private var fileDatas = [Data]() | |
init(url: URL) { | |
self.url = url | |
} | |
var urlRequest: URLRequest { | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") | |
request.httpBody = body | |
return request | |
} | |
mutating func addFormField(named name: String, value: String) { | |
var fieldString = "--\(boundary)\r\n" | |
fieldString += "Content-Disposition: form-data; name=\"\(name)\"\r\n" | |
fieldString += "\r\n" | |
fieldString += "\(value)\r\n" | |
formFields.append(fieldString) | |
} | |
mutating func addFileData(fieldName: String, fileName: String, mimeType: String, fileData: Data) { | |
let data = NSMutableData() | |
data.append(string: "--\(boundary)\r\n") | |
data.append(string: "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n") | |
data.append(string: "Content-Type: \(mimeType)\r\n\r\n") | |
data.append(fileData) | |
data.append(string: "\r\n") | |
let result: Data = data as Data | |
fileDatas.append(result) | |
} | |
private var body: Data { | |
let body = NSMutableData() | |
for field in formFields { | |
body.append(string: field) | |
} | |
for fileDatum in fileDatas { | |
body.append(fileDatum) | |
} | |
body.append(string: "--\(boundary)--") | |
return body as Data | |
} | |
} | |
fileprivate extension NSMutableData { | |
func append(string: String) { | |
if let data = string.data(using: .utf8) { | |
self.append(data) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment