enter image description hereenter image description hereenter image description hereI am using Alamofire. I am stuck in posting the post request.
I have a post body which is -
[
{
"siteName": "lab1",
"locationCode": "111",
"locationName": "test1"
}
]
How should I make the request call? I am doing -
let parameters: Parameters = [
"siteName": "lab",
"locationCode": "1156",
"locationName": "123test"
]
Alamofire.request(URLStr, method: .post, parameters: parameters , encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
sucessHandler(json)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
failureHandler(response.error)
}
}
Thank you so much guys. I found the other way of doing this.
let fileUrl = NSURL(string: URLStr)
var request = URLRequest(url:fileUrl as! URL )
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let values = [parameters]
request.httpBody = try! JSONSerialization.data(withJSONObject: values)
Alamofire.request(request)
.responseJSON { response in
// do whatever you want here
switch response.result {
case .failure(let error):
print(error)
if let data = response.data, let responseString = String(data: data, encoding: .utf8) {
print(responseString)
failureHandler(response.error)
}
case .success(let responseObject):
print(responseObject)
do {
let user = try IeroLocationSave(JSONDecoder(response.data ?? "nil..12"))
//print("city is: \(user.address.city)")
sucessHandler(user)
//That's it! The object has all the appropriate properties mapped.
} catch {
print("unable to parse the JSON")
}
}
}
Below code works for me
let parameters: Parameters = ["feedback_name": "SwiftTest","feedback_email":"m#m.com","feedback_description":"Test"]
Alamofire.request("http://212.69.45.77:8082/api/feedbackapp",method: .post,parameters: parameters).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
Related
I am trying to uploading some bytes to a server using alamofire, my code is as follows:
let parameters: Parameters = ["data": data]
let headers: HTTPHeaders = ["Content-Type": "application/vnd.awallet-signed-orders-v0"]
Alamofire.request(query, method: .put,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers).responseJSON { response in
print("Request: \(String(describing: response.request))") // original url request
print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
if let json = response.result.value {
let parsedJSON = try! JSON(parseJSON: (json as! String))
callback(parsedJSON["orders"]["accepted"])
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
}
The data is a [UInt8] however doing this makes alamofire cast the bytes as a string, if the array is [0,0] it becomes "0,0", this is not what I want as I want it to upload the bytes directly.
Is there a way to do this in alamofire?
Note: I don't want to cast it to a hex string as this is not efficient
Solved, just need to use the upload method and convert bytes to data
var hexMessageData = signedOrders[0].message
let headers: HTTPHeaders = ["Content-Type": "application/vnd.awallet-signed-orders-v0"]
Alamofire.upload(Data(bytes: hexMessageData), to: query, method: .put, headers: headers).response { response in
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
callback(data.hexEncoded)
}
}
i want to upload photo into server with almofire i'm using this code right now but i'm getting timeout
let imageData = UIImageJPEGRepresentation(croppedImage, 1)
let urlRequest = self.urlRequestWithComponents(url, imageData: imageData!)
self.alamofire.upload(urlRequest.1, to: urlRequest.0 as! URLConvertible).responseJSON { response in
guard response.result.isSuccess else {
self.showError()
return
}
guard let data = response.result.value else {
self.showError()
return
}
let json = JSON(data)
}
func urlRequestWithComponents(_ urlString:String, imageData:Data) -> (URLRequestConvertible, Data) {
var urlRequest = URLRequest(url: URL(string: urlString)!)
urlRequest.httpMethod = HTTPMethod.post.rawValue
let boundary = generateBoundaryString()
let contentType = "multipart/form-data;boundary=" + boundary
urlRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
let uploadData = NSMutableData()
uploadData.append("\r\n--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Disposition: form-data; name=\"file\"; filename=\"file.png\"\r\n".data(using: String.Encoding.utf8)!)
uploadData.append("Content-Type: image/png\r\n\r\n".data(using: String.Encoding.utf8)!)
uploadData.append(imageData)
uploadData.append("\r\n--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return try! (Alamofire.URLEncoding.default.encode(urlRequest, with: nil), uploadData as Data)
}
Is there any solution about this issue ?
Try this in swift 3
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(imageData, withName: "photo_path", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
}, to:"http://server1/upload_img.php")
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
})
upload.responseJSON { response in
//self.delegate?.showSuccessAlert()
print(response.request) // original URL request
print(response.response) // URL response
print(response.data) // server data
print(response.result) // result of response serialization
// self.showSuccesAlert()
//self.removeImage("frame", fileExtension: "txt")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
case .failure(let encodingError):
//self.delegate?.showFailAlert()
print(encodingError)
}
}
I've got a old codebase that I'm trying to migrate out of. The network calls currently use Alamofire 4.0 and I'm trying to use URLSession instead. I'm having trouble figuring out what's wrong, here's what I've been doing. I start off with the route and params that I want to post:
// route to user creation
let url = ...
let params = ["user": ["first_name": "John", "last_name": "Appleseed", "email": "john#apple.com", "password": "asdfgh"]]
Here's the old and new network calls:
// old network request
Alamofire.request(url, method: .post, parameters: newUser, encoding: JSONEncoding.default).responseJSON { response in
// ...
}
// new code
var request = URLRequest(url: url)
let jsonData = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
request.httpBody = jsonData
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { return print("error=\(error)") }
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("status code should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
For some reason, I'm getting a status code of 400 in my URLSession attempt. Alamofire works fine.
Any advice appreciated.
The problem is that the request isn't recognized as a JSON call. Write the following assignment after you create your URLRequest:
request.allHTTPHeaderFields = ["Content-Type": "application/json"]
I'm new to iOS and I would like some direction on why my code isn't working. I'm trying to make a call to a url and pass a token and get the response. My response is coming back with a 404 status code.
let reverse = ["token": "831b21c47a7f7daee7d6e4e3fa11deaa"]
let url = "http://challenge.com"
Alamofire.request(url, parameters: reverse).responseJSON { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try bellow code:
Alamofire.request(url, method: .get, parameters: reverse, encoding: JSONEncoding.default).responseString { response in
print(response.request) // original URL request
print(response.response) // HTTP URL response
print(response.data) // server data
print(response.result) // result of response serialization
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Try this Code:
This code is also handle the error when response will be the blank and also the Internet connection is disable.
func apiCall(params : [String:AnyObject],block:([String:AnyObject]->Void)?) {
if Reachability.isConnectedToNetwork(){
Alamofire.request(.POST, URL, parameters: params, encoding: .JSON, headers: nil).responseJSON{
response in
let data = response.result.value
if data == nil{
if response.result.error?.code == -1005 {
print(response.result.error?.localizedDescription)
}
else{
switch response.result {
case .Success:
block!(data as! [String:AnyObject])
case .Failure(let error):
print(error)
}
}
}
}
else{
print(NO_NETWORK)
}
}
strong text this is my code to pass two parameters(jsonData and device_Secret) to httpBody for that i should get following son in response
{"success":false,"msg":"Key not created plz try again."}
but i m getting this
responseString = Optional({"success":false,"msg":"Invalid Method"})
there is a problem in parameters format, what i am doing wrong?
my code is following /////////////
let JsonData = ["method":"device_token","params":["key":"1234jhg","device_id":"eb7e630a9637b0b83557e5a62121be8cb9210afb9aa5b878f819b775cb7d42a6"]]
let device_secret = ["params":["token":"-1","device_id":"9de47fb53c67eca4","key":"-1"]]
let params = ["data":JsonData, "device_secret":device_secret] as Dictionary<String, AnyObject>
let request = NSMutableURLRequest(URL: NSURL(string: "http://dev.jobsmarket.pk/api/v1")!)
print(request)
request.HTTPMethod = "POST"
let data : NSData = NSKeyedArchiver.archivedDataWithRootObject(params)
print("NSdata of params is")
print(data)
NSJSONSerialization.isValidJSONObject(params)
print( NSJSONSerialization.isValidJSONObject(params))
// request.HTTPBody = params
request.HTTPBody = NSKeyedArchiver.archivedDataWithRootObject(params)
print("httpBody is ")
print(request.HTTPBody)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
guard error == nil && data != nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
}
task.resume()
/////////////////////////