Swift 4.2 code equivalent for SAP's Leonardo API [duplicate] - swift

This question already has answers here:
Upload image with parameters in Swift
(3 answers)
Closed 4 years ago.
Getting HTTP 400 error while connecting with SAP Leonardo sandbox server using scene text recognition API
SAP provides boilerplate code in older version of swift. I have used curl command and the API and works. But its not working when I try and convert the code into swift 4.2 version. I am attaching the code below.
func connectWithSAP(photoURL : URL, photoData : String, sentImageData : Data){
if let myNewURL = URL(string: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition") {
var myRequest = URLRequest(url: myNewURL)
myRequest.addValue("multipart/form-data; --\(boundary)", forHTTPHeaderField: "Content-Type")
myRequest.addValue("application/json", forHTTPHeaderField: "Accept")
myRequest.addValue("xxxxxxxxxxx", forHTTPHeaderField: "APIKey")
myRequest.httpMethod = "POST"
myRequest.cachePolicy = .reloadIgnoringLocalCacheData
myRequest.timeoutInterval = 60.0
// Constructing the body of the request.
var data = Data()
var dataString = ""
dataString.append("--\(boundary)\r\n")
dataString.append(contentsOf: "Content-Disposition:form-data; name=\"files\"; filename=\"Image1.jpeg\" \r\n")
dataString.append(contentsOf: ";Content-Type:image/jpeg \r\n\r\n")
dataString.append(photoData)
dataString.append("--\(boundary) ----- \r\n")
data = dataString.data(using: .utf8)!
myRequest.httpBody = data
let task = URLSession.shared.dataTask(with: myRequest) { (data, response, error) in
if let error = error {
print(error)
}
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print(error as Any)
// Getting output at this stage, which is shown below
return }
if let mimeType = httpResponse.mimeType,
mimeType == "application/json",
let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print(json as Any)
}catch {
print(error)
}
}
}
task.resume()
}
I am getting a following details in my response object
{ URL: https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition } { Status Code: 400, Headers {\n Connection = (\n \"keep-alive\"\n );\n \"Content-Length\" = (\n 131\n );\n \"Content-Type\" = (\n \"application/json\"\n );\n Date = (\n \"Sat, 16 Feb 2019 11:56:37 GMT\"\n );\n Server = (\n \"Werkzeug/0.14.1 Python/3.5.5\"\n );\n \"Strict-Transport-Security\" = (\n \"max-age=31536000; includeSubDomains; preload;\"\n );\n \"X-Vcap-Request-Id\" = (\n \"fea7037c-4e48-49d2-4be1-53b0dad0ee46\"\n );\n}
As you would see the status code is HTTP 400. Need some help in getting the right response and data from the server.

Most probably, the body data got messed up. Here's the working code:
let boundaryConstant = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
let headers = [
"APIKey": "YourAPIKEY"
]
let contentType = "multipart/form-data; boundary=" + boundaryConstant
//API endpoint for API sandbox
var request = URLRequest(url: URL(string: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition")!)
//setting request method
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let path1 = Bundle.main.path(forResource: "your_image", ofType: "png")!
let url = URL(fileURLWithPath: path1)
let fileName = url.lastPathComponent
let data = try? Data(contentsOf: url)
let imageData = UIImage.init(data: data!)!
let pngData = UIImagePNGRepresentation(imageData)!
let mimeType = "image/png"
let boundaryStart = "--\(boundaryConstant)\r\n"
let boundaryEnd = "--\(boundaryConstant)--\r\n"
let fieldName = "files"
let contentDispositionString = "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(fileName)\"\r\n"
let contentTypeString = "Content-Type: \(mimeType)\r\n\r\n"
var body = Data()
body.append(boundaryStart.data(using: .utf8)!)
body.append(contentDispositionString.data(using: .utf8)!)
body.append(contentTypeString.data(using: .utf8)!)
body.append(pngData)
body.append("\r\n".data(using: .utf8)!)
body.append(boundaryEnd.data(using: .utf8)!)
request.httpBody = body
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
let dataTask = session.dataTask(with: request) { (data, response, error) in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
}
dataTask.resume()
You can also use Alamofire to upload image. It's way cleaner, don't need to play around with "body" much:
let headers: HTTPHeaders = [
"APIKey": "<<Your API KEY>>",
"Content-type": "multipart/form-data"
]
let parameters:[String: String] = [:] //any other parameters you need to send
let path1 = Bundle.main.path(forResource: "<<your_image>>", ofType: "<<png or jpeg>>")!
let url = URL(fileURLWithPath: path1)
let fileName = url.lastPathComponent
let data = try? Data(contentsOf: url)
let imageData = UIImage.init(data: data!)!
//converting it into png data
let pngData = UIImagePNGRepresentation(imageData)
let mimeType = "image/png"
let fieldName = "files"
Alamofire.upload(multipartFormData: { (multipartFormData) in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
if let data = pngData{
multipartFormData.append(data, withName: fieldName, fileName: fileName, mimeType: mimeType)
}
}, usingThreshold: UInt64.init(), to: "https://sandbox.api.sap.com/ml/scenetextrecognition/scene-text-recognition" , method: .post, headers: headers) { (result) in
switch result{
case .success(let upload, _, _):
upload.responseJSON { response in
print("Succesfully uploaded")
}
case .failure(let error):
print("Error in upload: \(error.localizedDescription)")
}
}

Related

API call for Multipart/form_data Body with application/json data

I am trying to upload some data to my server.I am tring to put my data in file and upload.The request body is multipart/form_data with a single parameter named "filemessage" containing text data which has a content-type of application/json
I am not sure how to handle the application/json as content-type for inner data contained by "filemessage".
I am getting 500 internal server error
{
"erMessage": "Unknown error",
"erCode": "UnknownErCode"
}
Here is the code.
func testMultipart()
{
let path = Bundle.main.path(forResource: "testregister", ofType: "txt")
do {
let mtext = try String(contentsOfFile: path!)
let dataA = Data(mtext.utf8)
guard let url = URL(string: "MY URL") else { return false }
var request = URLRequest(url: url)
request.httpMethod = "POST"
let mKey = "filemessage"
let mFileName = "testregister"
let mMimeType = "text/plain"
let boundary = generateBoundary()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let lineBreak = "\r\n"
var body = Data()
body.append("--\(boundary + lineBreak)")
body.append("Content-Disposition: form-data; name=\"\(mKey)\"; filename=\"\(mFileName)\"\(lineBreak)")
body.append("Content-Type: \(mMimeType + lineBreak + lineBreak)")
body.append(dataA)
body.append(lineBreak)
request.httpBody = dataA
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
}.resume()
}
catch(_){print("error")}
}
func generateBoundary() -> String
{
return "Boundary-\(NSUUID().uuidString)"
}

Swift: How to add Dictionary format in forHTTPHeaderField in GET request

In GET request, I am trying to add header.
request.setValue(value: String?, forHTTPHeaderField: "SessionInfo")
But, SessionInfo value is in [String : Any]
Attempt 1:
func SO_Function() {
let service_url = WebService.sharedManager().serviceURL
let getMenuURL = service_url + "/MyPage/FileDownload.ashx"
var convertedString = ""
do {
let data1 = try JSONSerialization.data(withJSONObject: WebService.sharedManager().mobInfoDict, options: [])
convertedString = String(data: data1, encoding: .utf8)!
print("\n\nconvertedJSONtoData ", convertedString)
} catch {
print("\n\nCAtcLL___Err ",error.localizedDescription)
}
let url = NSURL(string: getMenuURL)
let request = NSMutableURLRequest(url: url! as URL)
//Below line, If I can able to add [String:Any] then I will get
proper Image as output.
request.setValue(convertedString, forHTTPHeaderField: "SessionInfo")
request.setValue("67a2a6fb1d13450a", forHTTPHeaderField: "Flowid")
request.setValue("d29566ac42de4e99", forHTTPHeaderField: "Fileid")
request.setValue("LMS_LEAVEREQUEST", forHTTPHeaderField: "Form")
request.httpMethod = "GET"
let session = URLSession.shared
let mData = session.dataTask(with: request as URLRequest) { (data, response, error) -> Void in
if let res = response as? HTTPURLResponse {
DispatchQueue.main.async {
let img = UIImage(data: data!)
self.attachmentImgVw.image = img
}
}else{
print("\n\nError: \(String(describing: error))")
}
}
mData.resume()
}
Output
The data couldn’t be read because it isn’t in the correct format.
Error ScreenShot 1:
Postman Screenshot
In postman, I am giving SessionInfo value as in Dictionary format. Working fine.
How to solve this issue?

401 Forbidden when sending email with Swift and Mailgun

I have the following code but consistently get error 401 forbidden when attempting to run it:
func email() {
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/{edited_out}/messages")! as URL)
request.httpMethod = "POST"
let data = "from: Swift Email <(test#test.com)>&to: [my_email_address#gmail.com,(my_email_address#gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
request.httpBody = data.data(using: String.Encoding.ascii)
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("key-{edited_out}", forHTTPHeaderField: "api")
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The error is:
url = https://api.mailgun.net/v3/{edited_out}/messages
response = <NSHTTPURLResponse: 0x600000226a20> { URL: https://api.mailgun.net/v3/{edited_out}/messages } { status code: 401, headers {
Connection = "keep-alive";
"Content-Length" = 9;
"Content-Type" = "text/html; charset=utf-8";
Date = "Thu, 29 Dec 2016 21:22:46 GMT";
Server = nginx;
"Www-Authenticate" = "Basic realm=\"MG API\"";
} }
response code = 401
If I send such a request via curl with my credentials it works fine.
Any ideas?
You need to set the uesrname and the password.
Something like this:
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
and base64Credentials is the :
let credentials= String(format: "%#:%#", username, password)
let base64Credentials= credentials.data(using: String.Encoding.utf8)!
Finally got it working with the following code, if it helps anyone else:
func email() {
let session = URLSession.shared
let request = NSMutableURLRequest(url: NSURL(string: "https://api.mailgun.net/v3/{edited_out}/messages")! as URL)
request.httpMethod = "POST"
let credentials = "api:key-{omitted}"
request.setValue("Basic \(credentials.toBase64())", forHTTPHeaderField: "Authorization")
let data = "from: Swift Email <(test#test.com)>&to: [my_email_address#gmail.com,(my_email_address#gmail.com)]&subject:Hello&text:Testing_some_Mailgun_awesomness"
request.httpBody = data.data(using: String.Encoding.ascii)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.url!)")
print("response = \(response)")
let httpResponse = response as! HTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
extension String {
func fromBase64() -> String? {
guard let data = Data(base64Encoded: self) else {
return nil
}
return String(data: data, encoding: .utf8)
}
func toBase64() -> String {
return Data(self.utf8).base64EncodedString()
}
}
So I guess the answer from William would have worked with:
let base64Credentials = credentials.data(using: String.Encoding.utf8)!.base64EncodedString()
Instead of:
let base64Credentials = credentials.data(using: String.Encoding.utf8)!

Swift 3 How To Send A Multipart Post Request With Vapor

I'm using vapor to host images for my app.I have the following code to recieve the image and print it.
drop.post("saveArt") { request in
if let contentType = request.headers["Content-Type"], contentType.contains("image/png"), let bytes = request.body.bytes {
let image = NSImage(data: Data(bytes))
print(image)
return JSON(["Testawesome":"awesome123"])
}
return JSON(["test":"123"])
}
How can I send a multipart request using just swift?.Here is the current post request code i'm using.
let tiffData = imagetosend?.tiffRepresentation
let imageRep = NSBitmapImageRep(data: tiffData!)
let image_data = imageRep?.representation(using: .JPEG, properties: [:])
print("Hi")
let url = NSURL(string: "http://localhost:8080/getArt")
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST"
//define the multipart request type
request.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
let mimetype = "image/png"
//define the data post parameter
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(image_data!)
body.append("\r\n".data(using: String.Encoding.utf8)!)
request.httpBody = body as Data
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response , error == nil else {
print(error?.localizedDescription)
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString)
}
task.resume()
I solved it using this alamofire method.
Alamofire.request("YOUR URL", method: .post, parameters: parm, encoding: JSONEncoding.default).responseJSON(completionHandler: { json in
// If you want to return json.
print(json)
})

Swift 3 Multipart form/data Upload- URLSession gets 206 response code/Alamofire receives 406

I am trying to upload data to our server. The data is a zip file converted in to Data.
SSZipArchive.createZipFile(atPath: "\(self.currentWPDirectory!)/\(self.documentId!).zip", withFilesAtPaths: checkInFileList)
let zipData = try! Data(contentsOf: URL(string: "file:///\(self.currentWPDirectory!)/\(self.documentId!).zip")!)
URLSession
let parameters = "?documentId=\(self.documentId!)&documentAction=CHECKIN&doc_action_comment=some comment&device_name=\(UIDevice.current.name)"
let urlString = "\(Constants.WebService.checkIn)\(parameters)"
let url = urlString.replacingOccurrences(of: " ", with: "%20")
let request = NSMutableURLRequest(url: URL(string: url)!)
let data = zipData
request.httpMethod = HTTPMethod.post.rawValue
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request.setValue(contentType, forHTTPHeaderField:"Content-Type")
let body = NSMutableData();
let tempData = NSMutableData()
let fileName = "FILE_NAME" + ".zip"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
let fileNameContentDisposition = fileName != "" ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.append(contentDisposition.data(using: String.Encoding.utf8)!)
tempData.append("Content-Type: \(mimeType)\r\n\r\n".data(using: String.Encoding.utf8)!)
tempData.append(zipData)
tempData.append("\r\n".data(using: String.Encoding.utf8)!)
body.append(tempData as Data)
body.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
request.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request.httpBody = body as Data
let session = URLSession(configuration: URLSessionConfiguration.default)
let task = session.uploadTask(with: request as URLRequest, from: data) { (data, response, err) in
// Gets 206 in response
}
task.resume()
Alamofire
let params = [
"documentId": self.documentId!,
"documentAction": (self.isSync) ? "SYNC" : "CHECKIN",
"doc_action_comment": "Some Comment",
"device_name": UIDevice.current.name
]
Alamofire.upload(
multipartFormData: { multipartFormData in
multipartFormData.append(zipData, withName: "FILE_DATA", fileName: "\(self.documentId!).zip", mimeType: "application/zip")
for (key, value) in params {
multipartFormData.append((value as! String).data(using: .utf8)!, withName: key)
}
},
to: "\(Constants.WebService.checkIn)?documentId=\(self.documentId!)&documentAction=\((self.isSync) ? "SYNC" : "CHECKIN")&doc_action_comment=comment&device_name=\(UIDevice.current.name)",
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(response)
// Get 406 Response code
// Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 0."
}
self.completionCallback!(true)
}
case .failure(let encodingError):
print(encodingError)
self.completionCallback!(false)
}
}
)
I have tried many ways to get multipart form/data uploads to send my data, with no success. Can anyone point me in the right direction?