Request time out error 1001 using alamofire in ios swift? - ios

Here i am sending parameter value like username, user toke, post id, etc to backend using alamofire. if status success then, notification will will send from backend. Inside postnotification function i have tried post method code using alamofire and datatask method but it does not work. In console i am getting request time out or nothing.
Here is my code :
func postNotification(postItem: String, post: Post) {
// declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")
//create the url with URL
var parameters = [String:Any]()
parameters["count"] = post.likeCount!
parameters["likedby"] = currentName
parameters["postId"] = postItem
parameters["token"] = post.token!
let Url = String(format: "http://highavenue.co:9000/likesnotification")
guard let serviceUrl = URL(string: Url) else { return }
// let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
let parameterDictionary = ["username" : "Test", "password" : "123456"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
}catch {
print(error)
}
}
}.resume()
// let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
//
// Alamofire.request("http://highavenue.co:9000/likesnotification", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
// // original URL request
// print("Request is :",response.request!)
//
// // HTTP URL response --> header and status code
// print("Response received is :",response.response)
//
// // server data : example 267 bytes
// print("Response data is :",response.data)
//
// // result of response serialization : SUCCESS / FAILURE
// print("Response result is :",response.result)
//
// debugPrint("Debug Print :", response)
//
//
// }
// Alamofire.request("http://highavenue.co:9000/likesnotification", method: HTTPMethod.post, parameters: json, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
//
// // original URL request
// print("Request is :",response.request!)
//
// // HTTP URL response --> header and status code
// print("Response received is :",response.response)
//
// // server data : example 267 bytes
// print("Response data is :",response.data)
//
// // result of response serialization : SUCCESS / FAILURE
// print("Response result is :",response.result)
//
// debugPrint("Debug Print :", response)
// }
}
Any help much appreciated pls..

Yaah solved it. There was a negligence mistake. I used an additional slash in the URL. I changed the web API to a different folder and I made this mistake while changing it in the iOS code. and Also Set your timeout interval here.
let RequestData = NSMutableURLRequest(URL: NSURL.init(string: "Your URL Hear")!)
RequestData.HTTPMethod = "POST"
RequestData.timeoutInterval = 250 // Time interval here.
Alamofire.request(RequestData).responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) { // response
print(responseData.result.value!)
}
}
Hope this Help You..

Related

how to upload the IAP base64 receipt to the server?

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?
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/

iOS Swift Http request post method using header x-www-form-urlencoded?

I have to make an API call with headers as application/x-www-form-urlencoded value as a JSON string. When give parameter value and header in postman, it works fine and returns status code 200 ok. Here i am using backend node js . Post method does not work in front end. Dont know what is the issue.
Errors:
Sometimes i am getting request time out,
NSUrlfailingstring, finished with status code 1001
Here is the code of my backend :
var status = {
SUCCESS : 'success',
FAILURE : 'failure'
}
var httpStatus = {
OK : HttpStatus.OK,
ISE : HttpStatus.INTERNAL_SERVER_ERROR,
BR : HttpStatus.BAD_REQUEST
}
exports.likes= function(req, res){
var Username =req.body.username;
var likecount=req.body.count;
var likedby = req.body.likedby;
var postId = req.body.postId;
var tokenId = req.body.tokenId;
var message = {
to: tokenId,
collapse_key: '',
data: {
name:Username,
Message:"Content about message",
Redirect:"TopostId : "+postId,
time: ""
},
notification: {
title: "Hey Buddy , Someone have liked your post",
body: likedby +"Likedyourpost",
icon: "notification"
}
};
fcm.send(message)
.then(function (response) {
console.log("Successfully sent with response: ", response);
res.status(httpStatus.OK).json({
status: status.SUCCESS,
code: httpStatus.OK,
error:''
});
return;
})
.catch(function (err) {
console.log(err);
});
};
module.exports = function(app) {
app.post('/likesnotification', notification.likes);
app.post('/commentsnotification', notification.comments);
app.post('/othernotification', notification.othernot);
app.post('/followrequset', notification.followreq);
app.post('/followresponse', notification.followres);
app.post('/publicaccountfollow', notification.publicacfollow);
};
Here is my front code in ios Swift:
Try 1:
func postNotification(postItem: String, post: Post) {
print("Get token from post:::",post.token)
print(postItem)
let token = UserDefaults.standard.string(forKey: "token")
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}
Try 2:
var parameters = [String:Any]()
parameters["count"] = post.likeCount!
parameters["likedby"] = currentName
parameters["postId"] = postItem
parameters["token"] = post.token!
let Url = String(format: "http://highavenue.co:9000/likesnotification")
guard let serviceUrl = URL(string: Url) else { return }
// let loginParams = String(format: LOGIN_PARAMETERS1, "test", "Hi World")
let parameterDictionary = parameters
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {
return
}
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options:
[])
print(json)
}catch {
print(error)
}
}
}.resume()
Any help much appreciated pls.
I seen your code you are suppose to call the header parameter which was you create for it. You are not pass header in alamofire request method.
Like below :
let headers: HTTPHeaders = ["Content-Type" :"application/x-www-form-urlencoded"]
let parameters : [String:Any] = ["count":post.likeCount!, "likedby":currentName, "postId=":postItem, "token": post.token!]
Alamofire.request("http://highavenue.co:9000/likesnotification/", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case .success(_):
if let data = response.result.value{
print(data)
}
break
case .failure(_):
print(response.result.error as Any)
break
}
}
}

Swift - How to send POST request with "x-www-form-urlencoded" content-type

I searched a lot and there's no clear instruction for sending POST request with "x-www-form-urlencoded" content-type.
i want to know how to do that and if you know how to do it with Alamofire it would be even better.
any help will be appreciated.
Hope you are searching for this one or give us more explanation in code so we get it easily:
let headers = [
"Content-Type": "application/x-www-form-urlencoded"
]
let parameters = [
]
Alamofire.request("urlString", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response:DataResponse<Any>) in
switch(response.result) {
case.success(let data):
print("success",data)
case.failure(let error):
print("Not Success",error)
self.view.makeToast(message: "Server Error!!")
}
}
I used below code in swift 4.2
guard let url = URL(string: "http://192.168.88.129:81/authenticate") else {
return
}
let user1 = username.text!
let pass = passwordfield.text!
print(user1)
print(pass)
let data : Data = "username=\(user1)&password=\(pass)&grant_type=password".data(using: .utf8)!
var request : URLRequest = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type");
request.setValue(NSLocalizedString("lang", comment: ""), forHTTPHeaderField:"Accept-Language");
request.httpBody = data
print("one called")
let config = URLSessionConfiguration.default
let session = URLSession(configuration: config)
// vs let session = URLSession.shared
// make the request
let task = session.dataTask(with: request, completionHandler: {
(data, response, error) in
if let error = error
{
print(error)
}
else if let response = response {
print("her in resposne")
}else if let data = data
{
print("here in data")
print(data)
}
DispatchQueue.main.async { // Correct
guard let responseData = data else {
print("Error: did not receive data")
return
}
let decoder = JSONDecoder()
print(String(data: responseData, encoding: .utf8))
do {
// let todo = try decoder.decode(T.self, from: responseData)
// NSAssertionHandler(.success(todo))
} catch {
print("error trying to convert data to JSON")
//print(error)
// NSAssertionHandler(.failure(error))
}
}
})
task.resume()
}
Try this following method using Alamofire
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.default)
If it doesn't work, which is unlikely, use this following code
Alamofire.request("yourSide", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

Can't get correct api call in swift 3

I tried this particular API in postman, and it returns a fine result.
Thus, i created a parameter
["JsonRequest": "{\"header\":\"GetLocationListReq\",\"accessKey\":\"fakeKey\"}"]
but when i pass this parameter when calling this API using swift and alamofire in my Xcode project, i always get back an error.
For those who are interested, my apiRouter is
//
// WINAPIRouter.swift
// Winner21
//
// Created by Lin Hairui on 27/4/17.
// Copyright © 2017 Pioneers & Leaders (Publishers). All rights reserved.
//
import Foundation
import Alamofire
enum WINAPIRouter : URLRequestConvertible {
static let baseURL = Constant.baseURL
case get(String)
case create([String:Any],String?)
case delete(String)
func asURLRequest() throws -> URLRequest {
var method : HTTPMethod {
switch self {
case .get:
return HTTPMethod.get
case .create:
return HTTPMethod.post
case .delete:
return HTTPMethod.delete
}
}
let params:(Dictionary<String, Any>?) = {
switch self {
case .get, .delete:
return nil
case .create(let params, _):
var fieldParams = params
fieldParams["accessKey"] = Constant.kAPIAccessKey
let jsonData: NSData
do {
jsonData = try JSONSerialization.data(withJSONObject: fieldParams, options: JSONSerialization.WritingOptions()) as NSData
let jsonString = NSString(data: jsonData as Data, encoding: String.Encoding.utf8.rawValue) as! String
let authParam : [String : Any] = [
"JsonRequest" : jsonString
]
print("google was here \(authParam)")
return authParam
} catch _ {
print ("JSON Failure")
}
return nil
}
}()
let url : URL = {
return URL(string: Constant.baseURL)!
}()
var urlRequest = URLRequest(url: url)
// urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
// urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
urlRequest.httpMethod = method.rawValue
print("facebook was here = \(urlRequest.httpMethod!)")
let encoding = JSONEncoding.default
print("yahoo was here \(params)")
//let facejsonData = try! JSONSerialization.data(withJSONObject: params!, options: JSONSerialization.WritingOptions())
return try encoding.encode(urlRequest, with: params!)
}
}
And, i call the API using the following function.
Alamofire.request(WINAPIRouter.create(params, nil)).responseJSON
I think response from API is not in JSON, try to use URL encoding like below,
Alamofire.request(path, method: .get, parameters: parameters, encoding: URLEncoding.default, headers: nil) . responseString(completionHandler: { ( dataResponse ) in
/// print response
})

HTTP Request in Swift with POST method

I'm trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.
Example:
Link: www.thisismylink.com/postName.php
Params:
id = 13
name = Jack
What is the simplest way to do that?
I don't even want to read the response. I just want to send that to perform changes on my database through a PHP file.
The key is that you want to:
set the httpMethod to POST;
optionally, set the Content-Type header, to specify how the request body was encoded, in case server might accept different types of requests;
optionally, set the Accept header, to request how the response body should be encoded, in case the server might generate different types of responses; and
set the httpBody to be properly encoded for the specific Content-Type; e.g. if application/x-www-form-urlencoded request, we need to percent-encode the body of the request.
E.g., in Swift 3 and later you can:
let url = URL(string: "https://httpbin.org/post")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.httpMethod = "POST"
let parameters: [String: Any] = [
"id": 13,
"name": "Jack & Jill"
]
request.httpBody = parameters.percentEncoded()
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard
let data = data,
let response = response as? HTTPURLResponse,
error == nil
else { // check for fundamental networking error
print("error", error ?? URLError(.badServerResponse))
return
}
guard (200 ... 299) ~= response.statusCode else { // check for http errors
print("statusCode should be 2xx, but is \(response.statusCode)")
print("response = \(response)")
return
}
// do whatever you want with the `data`, e.g.:
do {
let responseObject = try JSONDecoder().decode(ResponseObject<Foo>.self, from: data)
print(responseObject)
} catch {
print(error) // parsing error
if let responseString = String(data: data, encoding: .utf8) {
print("responseString = \(responseString)")
} else {
print("unable to parse response as string")
}
}
}
task.resume()
Where the following extensions facilitate the percent-encoding request body, converting a Swift Dictionary to a application/x-www-form-urlencoded formatted Data:
extension Dictionary {
func percentEncoded() -> Data? {
map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}
}
extension CharacterSet {
static let urlQueryValueAllowed: CharacterSet = {
let generalDelimitersToEncode = ":#[]#" // does not include "?" or "/" due to RFC 3986 - Section 3.4
let subDelimitersToEncode = "!$&'()*+,;="
var allowed: CharacterSet = .urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}()
}
And the following Decodable model objects facilitate the parsing of the application/json response using JSONDecoder:
// sample Decodable objects for https://httpbin.org
struct ResponseObject<T: Decodable>: Decodable {
let form: T // often the top level key is `data`, but in the case of https://httpbin.org, it echos the submission under the key `form`
}
struct Foo: Decodable {
let id: String
let name: String
}
This checks for both fundamental networking errors as well as high-level HTTP errors. This also properly percent escapes the parameters of the query.
Note, I used a name of Jack & Jill, to illustrate the proper x-www-form-urlencoded result of name=Jack%20%26%20Jill, which is “percent encoded” (i.e. the space is replaced with %20 and the & in the value is replaced with %26).
See previous revision of this answer for Swift 2 rendition.
Swift 4 and above
func postRequest() {
// declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
let parameters: [String: Any] = ["id": 13, "name": "jack"]
// create the url with URL
let url = URL(string: "www.thisismylink.com/postName.php")! // change server url accordingly
// create the session object
let session = URLSession.shared
// now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
// add headers for the request
request.addValue("application/json", forHTTPHeaderField: "Content-Type") // change as per server requirements
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
// convert parameters to Data and assign dictionary to httpBody of request
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: Any] {
print(jsonResponse)
// handle json response
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
// perform the task
task.resume()
}
For anyone looking for a clean way to encode a POST request in Swift 5.
You don’t need to deal with manually adding percent encoding.
Use URLComponents to create a GET request URL. Then use query property of that URL to get properly percent escaped query string.
let url = URL(string: "https://example.com")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!
components.queryItems = [
URLQueryItem(name: "key1", value: "NeedToEscape=And&"),
URLQueryItem(name: "key2", value: "vålüé")
]
let query = components.url!.query
The query will be a properly escaped string:
key1=NeedToEscape%3DAnd%26&key2=v%C3%A5l%C3%BC%C3%A9
Now you can create a request and use the query as HTTPBody:
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = Data(query.utf8)
Now you can send the request.
Heres the method I used in my logging library: https://github.com/goktugyil/QorumLogs
This method fills html forms inside Google Forms.
var url = NSURL(string: urlstring)
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData.dataUsingEncoding(NSUTF8StringEncoding)
var connection = NSURLConnection(request: request, delegate: nil, startImmediately: true)
let session = URLSession.shared
let url = "http://...."
let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
var params :[String: Any]?
params = ["Some_ID" : "111", "REQUEST" : "SOME_API_NAME"]
do{
request.httpBody = try JSONSerialization.data(withJSONObject: params, options: JSONSerialization.WritingOptions())
let task = session.dataTask(with: request as URLRequest as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
print ("data = \(jsonResponse)")
}catch _ {
print ("OOps not good JSON formatted response")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
All the answers here use JSON objects. This gave us problems with the
$this->input->post()
methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly.
We used this method to do it WITHOUT JSON
func postRequest() {
// Create url object
guard let url = URL(string: yourURL) else {return}
// Create the session object
let session = URLSession.shared
// Create the URLRequest object using the url object
var request = URLRequest(url: url)
// Set the request method. Important Do not set any other headers, like Content-Type
request.httpMethod = "POST" //set http method as POST
// Set parameters here. Replace with your own.
let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
request.httpBody = postData
// Create a task using the session object, to run and return completion handler
let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
guard error == nil else {
print(error?.localizedDescription ?? "Response Error")
return
}
guard let serverData = data else {
print("server data error")
return
}
do {
if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
print("Response: \(requestJson)")
}
} catch let responseError {
print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
let message = String(bytes: serverData, encoding: .ascii)
print(message as Any)
}
// Run the task
webTask.resume()
}
Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')
#IBAction func btn_LogIn(sender: AnyObject) {
let request = NSMutableURLRequest(URL: NSURL(string: "http://demo.hackerkernel.com/ios_api/login.php")!)
request.HTTPMethod = "POST"
let postString = "email: test#test.com & password: testtest"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){data, response, error in
guard error == nil && data != nil else{
print("error")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200{
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
}

Resources