Send image as base64 string through web service - swift

I have an app allow user upload a photo from photo library, first the app convert the image to base64 string and then pass the string to server through web service (C#.net).
Finally it is only work on some simple photos (e.g. black & white photos, small photos) but failed if color photos, I am not sure but i guess the base64 string truncated when passing to web server. (May be the string too long). Is it any problem on my code below?
func UploadPhoto(img: UIImage){
let strBase64 = img.jpegData(compressionQuality: 1)?.base64EncodedString() ?? ""
var request = URLRequest(url: URL(string: "https://xxxxx/uploadimg.asmx/UploadFile")!)
request.httpMethod = "POST"
let postString = "Base64String=" + strBase64
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request)
{
data, response, error in
if error == nil && data!.count > 0, let _ = data {
do
{
print ("API UploadFile Finished")
}
catch let error as NSError
{
print("UploadFile error")
print(error)
}
}
}
task.resume()
}

Related

Upload file (png, jpeg etc) in Web server with HTTP post request in Swift

I am developing an application in Swift language. I set up a backend service with amazon s3 service and fast api. I want to save an image with .png extension to this backend service. I am getting 422 "422 Unprocessable Entity" error from the server while sending the photo. I know this error occurs because the format is wrong but I couldn't fix the problem. I am sharing the part of the code I wrote in swift and the fast-api screenshot.
format
inputs
`func uploadImage2(paramName: String, fileName: String, image: UIImage, uid: String) {
let urlString = ""
let url = NSURL(string: urlString)!
let requestURL = NSMutableURLRequest(url: url as URL)
requestURL.httpMethod = "POST"
requestURL.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
let body = NSMutableData()
body.append("file=#\(image)".data(using: String.Encoding.utf8)!)
body.append("type=image/png".data(using: String.Encoding.utf8)!)
requestURL.httpBody = body as Data
let task = URLSession.shared.dataTask(with: requestURL as URLRequest){ data,response,error in
if let data = data {
let sendedData = String(data: data, encoding: .utf8)
print("Succesful + \(String(describing: sendedData))")
} else {
print("Error: \(String(describing: error))")
}
}
task.resume()
}`
I'm having trouble uploading photos to the server.

How can I read the content of a form-data when the response is in html(Swift)

I'm building an iOS application and I need to access the information on a website. I've located the API endpoint, and was able to get a result in Postman
screenshot of API header and form data
So far I have this code which can allow me to make the request, but how do I parse the response(which is an HTML form, then display response in app
var urlRequest = URLRequest(url: url!)
urlRequest.setValue("application/form-data",forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
urlRequest.httpBody = postString.data(using: .utf8)
urlRequest = .init(url: url!)```
I actually found a great resources that showed how to send POST Request with post body, and how to read the response
How To send POST Request
Now it's just a matter of parsing the HTML that is returned, and displaying it in app.
let url = URL(string: Constants.rankingAPI)
guard let requestUrl = url else {
fatalError()
}
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postString = "year=2021&season=Outdoor&province=ON&age_group=OPEN&age_sub_group_masters=ALL&age_sub_group_para=ALL&rankings_event=100m&best_by_athlete=1&rankings_event_spec_num=1&is_relay_EVENT=0&page=1"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString.htmlToString)")
}
}
task.resume()
}

How can I stay logged in when web scraping with URLSession?

With my program I try to login and scrape the home page, however after I log in with a post request (in which the response says successful), when I try to get the home page it says my session has timed out.
I've tried using different types of session, modifying minor parts of the code, and Alamofire with no success
import Foundation
let session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 30 // seconds
configuration.timeoutIntervalForResource = 30 // seconds
return URLSession(configuration: .default)
}()
let url = URL(string: "examplesite.com")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:
"Content-Type")
request.httpMethod = "POST"
let postString = "Email=exampleemail&Password=examplepass"
request.httpBody = postString.data(using: .utf8)
//log in
session.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode
!= 200 { // check for http errors
print("\(httpStatus.statusCode)")
print("\(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("\(responseString)")
let urlnext = URL(string: "example.com/HomePage")!
//get page after loggin in
session.dataTask(with: urlnext) { datanext, responsenext, errornext in
guard let datanext = datanext, errornext == nil else {
print("\(errornext)")
return
}
let stringnext = String(data: datanext, encoding: .utf8)
//get page html
print("\(stringnext)")
}.resume()
}.resume()
// Infinitely run the main loop to wait for our request.
// Only necessary if you are testing in the command line.
RunLoop.main.run()
the results are a successful login {\"msg\":\"\",\"valid\":\"1\"}, and the html code of a time out page instead of the home page

Get the HTML content when hitting URL in swift 3

My question is i want to hit the url and when i hit the url on server side the php return the results just echo in php and i have to save that result in variable in swift 3, i tried the below code:
let URLstr = URL(string: strURL)
let request = URLRequest(url: URLstr!)
request.httpMethod = "POST"
print (request)
I didn't get the content of URL in swift which is much easier in objective C.
Use the string initializer with the url.
do {
let contents = try String(contentsOf: URLstr, encoding: .ascii)
} catch {
// handle error
}
Or you can use URLSession.
let task = URLSession.shared.dataTask(with: URLStr) { data, response, error in
guard data != nil else { // no data }
let contents = String(data: data!, encoding: .ascii)
}
task.resume()
I adjusted the code provided above. To fetch HTML code use URLSession.
Swift 5
let session = URLSession.shared
let url = URL(string: "https://yourwebsiteaddress.com/")!
let task = session.dataTask(with: url) { data, response, error in
// Check whether data is not nil
guard let loadedData = data else { return }
// Load HTML code as string
let contents = String(data: loadedData, encoding: .utf8)
print(contents)
}
task.resume()

How can I make a call to load HTML content from a website?

I am trying to get HTML content from a website so I can display data within an app. How can I make a call for the HTML code in Swift 3?
Are you trying to actually load a webpage on the screen or just retrieve the HTML source as a String/Data object?
If you just need the HTML as a response object you can do something like the following:
if let url = URL(string: "http://www.example-url.com") {
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if error != nil {
print(error!)
} else {
if let unwrappedData = data {
let dataString = String(data: unwrappedData, encoding: .utf8)
// …handle string here…
}
}
}
task.resume()
}
Use UIWebView.
e.g.
let webView = UIWebView()
let url = URL(string: "http://yourwebsite")
let request = URLRequest(url: url)
webView.loadRequest(request)