Created
March 30, 2022 15:39
-
-
Save brian-lc/1c42a4f55d2a359cd370781ba03d1394 to your computer and use it in GitHub Desktop.
Upload example
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
private func doDataPult() { | |
playWaitingAnimation.toggle() | |
filename = imageUrl.lastPathComponent | |
let cardPost = CardPost(title: title, descr: descr, filename: filename, file: image.jpegData(compressionQuality: 1.0)!) | |
guard let uploadData = try? JSONEncoder().encode(cardPost) else { | |
return | |
} | |
//let url = URL(string: "http://127.0.0.1:8787/upload")! | |
let url = URL(string: "https://card.datapult.site/upload")! | |
var request = URLRequest(url: url) | |
request.httpMethod = "POST" | |
request.setValue("application/json", forHTTPHeaderField: "Content-Type") | |
//let (data, response, error) = try await URLSession.shared.uploadTask(with: request, from: uploadData) | |
let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in | |
if let error = error { | |
print ("error: \(error)") | |
return | |
} | |
guard let response = response as? HTTPURLResponse, | |
(200...299).contains(response.statusCode) else { | |
let httpResponse = response as? HTTPURLResponse | |
print ("server error: \(httpResponse?.statusCode ?? 999 )") | |
return | |
} | |
if let mimeType = response.mimeType, | |
mimeType == "application/json", | |
let data = data, | |
let dataString = String(data: data, encoding: .utf8) { | |
print ("got data: \(dataString)") | |
let cardRes = try! JSONDecoder().decode(CardResponse.self, from: data ) | |
DispatchQueue.main.async { | |
let newCard = CardModel(context: moc) | |
newCard.id = UUID() | |
newCard.cid = cardRes.cid | |
newCard.shareUrl = URL(string: cardRes.shareUrl) | |
newCard.web3Url = URL(string: cardRes.web3Url) | |
newCard.imageUrl = imageUrl // Local image file path from ios | |
newCard.filename = newCard.imageUrl?.lastPathComponent | |
newCard.title = title | |
newCard.descr = descr | |
newCard.img = image.jpegData(compressionQuality: 1.0) | |
print ("Created model") | |
try? moc.save() | |
print ("Saved model") | |
isNewPultPresented.toggle() | |
} | |
return | |
} | |
} | |
task.resume() | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment