Reputation: 1068
I used JSONEncoder to get the data and used the following code to upload the receipt to the server.
// send to server
let url = URL(string: "https://ios.jobyme88.com/KidsLearnHindi/save-shopping.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// check error
if let error = error {
print ("[shark-IAP] error: \(error)")
return
}
// check response
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print ("[shark-IAP] server error")
return
}
// print data from server
guard let data = data else {
print("[shark-IAP] no data")
return
}
let dataString = String(data: data, encoding: .utf8)
print ("[shark-IAP] got data: \(String(describing: dataString))")
}
task.resume()
But I found the string is too long that the server just receive empty string. Do you know how to upload the receipt?
Upvotes: 0
Views: 54
Reputation: 1540
I tried this myself some time ago and worked out the following solution for sending a receipt and receiving the validation result:
Base method to create and handle the HTTP request
func sendPost(url: URL, receiptBase64String: String) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.timeoutInterval = 15
let boundary = "Boundary-\(UUID().uuidString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let postParameters = ["receipt": receiptBase64String]
request.httpBody = self.createBodyWithParameters(boundary: boundary, parameters: postParameters)
let task = URLSession.shared.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
// TODO: Handle Server response
})
task.resume()
}
Helper method to create the request body as data
public func createBodyWithParameters(boundary: String, parameters: [String: String]?) -> Data {
let body = NSMutableData()
if let parameters = parameters {
for (key, value) in parameters {
body.append(string: "--\(boundary)\r\n")
body.append(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.append(string: "\(value)\r\n")
}
}
body.append(string: "--\(boundary)--\r\n")
return body as Data
}
Extension to allow appending to NSMutableData
private extension NSMutableData {
func append(string: String) {
if let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true) {
append(data)
}
}
}
Credits to http://swiftdeveloperblog.com/image-upload-example/
Upvotes: 1