I am getting error while making POST request with swift 4(iOS)
I am getting following debug description:
2017-11-09 23:12:57.283421+0300 ios1[35428:5830006]
Task <23DDE1DF-B58F-4A9E-9BB1-21571EE25661>.<1> HTTP load failed (error code: -1004 [1:61])
My code:
let dict = ["link": web.text, "addr": edit.text]
guard let uploadData = try? JSONEncoder().encode(dict) else { return }
let actInd = showActivityIndicatory(uiView: appView)
let url = URL(string: host)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.uploadTask(with: request, from: uploadData) { data, response, error in
if error != nil {
// handle the transport error
result = 2
print(error.debugDescription)
return
}
guard let response = response as? HTTPURLResponse, response.statusCode == 201 else {
result = 1
return
}
if response.mimeType == "text/plain" || response.mimeType == "text/plain", let data = data {
result = 0
print(data)
}
}
task.resume()
P.S.: I could see that request has been done correctly on server.
Thank you a lot
Related
I'm trying to create a function that will execute a post request to an API and I want the function to wait before it returns but it does not seem to work properly. I'm not sure what I'm missing.
As per the suggestion of another answer here on SO I'm using semaphores to accomplish this however it seems that it will "wait forever" since the app just hangs. I know the request is executed successfully and the app gets a response(tried with with prints all over the place).
This is what I've done so far:
func sendAuthRequest(username: String, password: String) -> Int {
let sem = DispatchSemaphore(value: 0)
var authStatus: Int = 0
let params = ["username":username, "password":password] as Dictionary<String, String>
var request = URLRequest(url: URL(string: Constants.api_base_url + "/auth/validateuser")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if let httpResponse = response as? HTTPURLResponse {
print(httpResponse.statusCode)
if (httpResponse.statusCode == 200) {
authStatus = 200
} else if (httpResponse.statusCode == 403) {
authStatus = 403
} else {
authStatus = 500
}
}
})
task.resume()
sem.wait()
return authStatus
}
Thanks!
If I restructure it quickly, I would do it this way:
func sendAuthRequest(username: String, password: String, completion: #escaping (Result<Int, Error>) -> Void) {
let params = ["username":username, "password":password] as Dictionary<String, String>
var request = URLRequest(url: URL(string: Constants.api_base_url + "/auth/validateuser")!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { data, response, error -> Void in
if let error = error {
completion(.failure(error))
return
}
if let httpResponse = response as? HTTPURLResponse {
var authStatus: Int
print(httpResponse.statusCode)
if (httpResponse.statusCode == 200) {
authStatus = 200
} else if (httpResponse.statusCode == 403) {
authStatus = 403
} else {
authStatus = 500
}
completion(.success(authStatus))
} else {
let error = NSError(domain:"", code: 0, userInfo:[NSLocalizedDescriptionKey: "Failed to get response"])
completion(.failure(error))
}
})
task.resume()
}
First time working on an apple swift project. I am building a library where I send an HTTP request to an API and I need to retrieve the cookies that are returned in the response but for some reason they are not being retrieved.
Below is the code that I have.
let url = URL(string: "http://192.168.1.118:500/initialise")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let parameters: [String: String] = [
"ApplicationID": app_id,
"DeviceID": "123456",
"AppVersion": app_version
]
request.setValue(api_key, forHTTPHeaderField: "authorisation-token")
//request.httpBody = parameters.percentEscaped().data(using: .utf8)
let postString = self.getPostString(params: parameters)
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) {data, response, error in
guard let data = data,
let response = response as? HTTPURLResponse,
error == nil else {
print("error", error ?? "Unknown Error")
return
}
guard(200...299) ~= response.statusCode else {
print("statusCode should 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
print ("HTTP Status Code: " + String(response.statusCode))
print ("-------Cookies--------")
let cookieStorage = HTTPCookieStorage.shared
let cookies = cookieStorage.cookies(for: URL(string:"192.168.1.118:500")!) ?? []
for cookie in cookies {
if cookie.name == "SESSIONID" {
MyClass.SESSIONID = cookie.value
}
else if cookie.name == "DO-LB" {
MyClass.DOLB = cookie.value
}
}
I've tried changing the cookieStorage.cookies URL to include and the port number 500 and exclude it but unfortunately neither of which has worked.
I am using trying to post some data to server using Swift URLRequest with using following code.
var request = URLRequest(url: URL(string: Global.ip)!)
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded; charset=UTF-8", forHTTPHeaderField: "Content-Type")
let postString = "cmd=getFavorites" + "&ab={\"userId\":\"\(userId)\",\"favId\":\"\(favoriteId)\",\"favoriData\":\(panelData)}&token=\(token)"
let newPostString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
request.httpBody = newPostString?.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(String(describing: error))")
completion(false)
return;
}
let json = JSON(data)
completion(true)
}
task.resume()
Im trying to upload an image through Dropbox HTTP API after authenticating, using NATIVE iOS functions and methods (cannot use ALAMOFIRE). When I send the request it gives me a timeout after 30 seconds.
...Code used:
let data = UIImagePNGRepresentation(self.image!)
var request = URLRequest.init(url: url)
request.allHTTPHeaderFields = [
"Authorization":"Bearer <TOKEN_HERE>",
"Dropbox-API-Arg":"{\"path\": \"/TCC/uploaded.png\",\"mode\": \"add\",\"autorename\": false,\"mute\": false}",
"Content-Type": "application/octet-stream",
]
URLSession.shared.uploadTask(with: request,
from: data) { returnData, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200
else {
if let callback = failure {
callback()
}
return
}
//UI updates in main thread
DispatchQueue.main.async() {
if success != nil {
success!()
}
}
}.resume()
Hello #Danilo Rodrigues,
There is a statement missing, you need to explicitly declare the method used:
let data = UIImagePNGRepresentation(self.image!)
var request = URLRequest.init(url: url)
request.allHTTPHeaderFields = [
"Authorization":"Bearer <TOKEN_HERE>",
"Dropbox-API-Arg":"{\"path\": \"/TCC/uploaded.png\",\"mode\": \"add\",\"autorename\": false,\"mute\": false}",
"Content-Type": "application/octet-stream",
]
request.httpMethod = "POST" //ADDED THIS LINE
URLSession.shared.uploadTask(with: request,
from: data) { returnData, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200
else {
if let callback = failure {
callback()
}
return
}
//UI updates in main thread
DispatchQueue.main.async() {
if success != nil {
success!()
}
}
}.resume()
Here I have to post base64encoded image to server. Below is my code which I am using:
func post_request_image(api:String){
if (imageview.image == nil)
{
return
}
let image_data = UIImageJPEGRepresentation(imageview.image!, 1.0)
if(image_data == nil)
{
return
}
loader.showLoadingAlert(view: self.view, title: "")
var web_apis_3 = api
// print(web_apis_3)
var request = URLRequest(url: URL(string: web_apis_3)!)
request.httpMethod = "POST"
do {
request.httpBody =
image_data?.base64EncodedString()
} catch let error {
print(error.localizedDescription)
}
// let content = String(data: json!, encoding:
String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
}
But it is giving me this error:
cannot assign value of type String to type Data
How can I resolve this?
if the server expects a string:
let image = UIImage(named: "sample")
guard let imgData = UIImagePNGRepresentation(image) else { return }
let base64String = imgData.base64EncodedString(options: .lineLength64Characters)
then submit base64String to the server in whatever way is needed.
for me I needed to submit:
let parameters: [String: String] = [
"image": base64String
]
since youre needing data, you should be able to submit imgData