Alamofire 4.0 ambiguous reference on upload - ios

I am trying to upload using alamofire, I am using the following code:
Alamofire.upload(urlRequest.0, to: urlRequest.1, method: .put)
.uploadProgress(queue: DispatchQueue.utility) { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
//Some code here
}
Where urlRequest is a tuple: (URLConvertible, Data). I am getting the compiler error : "Ambiguous reference to member 'upload(_:to:method:headers:)'". Any ideas what I am doing wrong here? Any pointers would be really appreciated! Thanks!

You may need to add the headers parameter:
Alamofire.upload(urlRequest.0, to: urlRequest.1, method: .put, headers: nil)
.uploadProgress { progress in
print("Upload Progress: \(progress.fractionCompleted)")
}
while a tuple's types should stand in this order: (Data, URLConvertible)

Related

post request with body Alamofire

I am trying to post some data to the API, but I keep getting Response status code was unacceptable: 404 error message.. I have checked, the POST parameters and API Url are all correct, example request works on the postman but it is not working on Xcode..
my POST request Url is in this format: {{API}}/postData/Id/block.
my POST request function with Alamofire is as follows:
func postData(token: String, id: String, category: String, completion: #escaping(_ data: DataTobePost) -> Void) {
let header: HTTPHeaders = ["authorization": token]
let parameter: Parameters = [
"Id": id,
"category": category ]
Alamofire.request(API_Configurator.postData, method: .post, parameters: parameter, encoding: JSONEncoding.default, headers: header).validate().responseData(completionHandler: { response in
switch response.result {
case .success(let val):
do {
let data = try JSONDecoder().decode(DataTobePost.self, from: val)
completion(data)
}catch {
print("[DataTobePost Catch Error while decoding response: \(error.localizedDescription)]")
}
case .failure(let error):
print("[DataTobePost Failure Error : \(error.localizedDescription)]")
}
})
}
and the response is:
{
"success": true
}
where am i going wrong, can anyone help through this. (I am quite new to Alamofire)
There is no way to check what is wrong.
If you got the 404 error it means 2 things:
Code was written correctly(it compiles)
Requested page does not exist (404 error)
I think you need to check your API_Configurator.postData.
Usually, it's something simple like extra characters like "//", " ", "." etc.
Or the problem with API.
The best way to check API uses Postman

Tracking progress in Alamofire Request [duplicate]

This question already has answers here:
Progress of a Alamofire request
(3 answers)
Closed 3 years ago.
I wanna know it is possible to show progress for request. I convert my images to base64 string and send it to my server with parameter. Is there a way to track it's progress? I wanna try something like that.But I cannot add progress section in my Alamofire.request. Is there something that I am missing?
Alamofire.request(.POST, URL, parameters: parameter, encoding: .JSON)
.progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in
// track progress here
}
.responseJSON { response in
// Do your stuff
}
Not sure but I think the current version of Alamofire uses downloadProgress instead of progress:
Alamofire.request(/* ... */).downloadProgress { progress in
progress.fractionCompleted // value between 0 and 1
}
.responseJSON { /* ... */ }
You can do like this
Alamofire.upload(multipartFormData: { (multipartFormData) in
}, with: URL, encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
// Here you get the progress
print(Progress.fractionCompleted)
})
upload.responseJSON { response in
case .failure( _ ):
}
})

Setting content-type header to use JSON with Swift 3 + AlamoFire

The answers in Alamofire Swift 3.0 Extra parameter in call did not work for me.
Setting header to nil compiles but I need ["Content-Type", "application/json"]. Here I get an error of an extra parameter in th emethod
How do I take
manager.request(url, method: .get, parameters: parameters).responseJSON {
response in
fulfill(response)
}
}
and send JSON content-type?
The documentation shows
Automatic Validation
Automatically validates status code within 200..<300 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in
switch response.result {
case .success:
print("Validation Successful")
case .failure(let error):
print(error)
}
}
I'm using .responseJSON but I'm not getting JSON back. So I think I need to send the Content-Type header.
Try this, there is another method overload that allow pass a dictionary with headers
let request = Alamofire.request(requestUrl, method: .get, parameters: [:], encoding: URLEncoding.queryString, headers: ["Content-Type" :"application/json"]).responseData { (response) in
/***YOUR CODE***/
}
for post JSON data in request check this answer Using manager.request with POST
Hope this helps you

Ambiguous reference to member upload alamofire

I am receiving this error when trying to upload a picture to my web server. I just copied and pasted the alamofire sample from github and I receive an error right away. My code is as follows:
let data = UIImageJPEGRepresentation(picOutlet.image, 0.5)
Alamofire.upload(.POST, "phpurlhere", file: photo)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.validate()
.responseJSON { response in
debugPrint(response)
}
UPDATE: I added JPEG representation to pass to alamofire function but still getting same error.
The issue is that the upload function:
Alamofire.upload(.POST, "phpurlhere", file: photo)
is expecting an object of type NSURL for the file: parameter. You are giving it a UIImage.
If your goal is to upload picOutlet.image using the upload function, try the following:
let data = UIImageJPEGRepresentation(picOutlet.image, 0.5)
Alamofire.upload(.POST, "phpurlhere", data: data)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWrite in
print(totalBytesWritten)
// This closure is NOT called on the main queue for performance
// reasons. To update your ui, dispatch to the main queue.
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.validate()
.responseJSON { response in
debugPrint(response)
}
try this
Alamofire.upload(photoURL, to: "phpurlhere", method: .post, headers:nil)
.uploadProgress { progress in // main queue by default
progressView.progress = Float(progress.fractionCompleted)
}
.downloadProgress { progress in // main queue by default
print("Download Progress: \(progress.fractionCompleted)")
}
.responseJSON { response in
debugPrint(response)
}

Deadlock inside NSURLSession delegate queue

I'm experiencing a deadlock inside one of the operations in the NSUrlSession delegate queue when using Alamofire.
it happens when i'm doing at least one download and one upload simultaneously (all requests are done through the default Alamofire manager). Is there any problem doing so from multiple threads? (either in NSUrlSession or Alamofire)
it seems to be stuck on __psynch_mutexwait in one of the operations in the NSURLSession delegate queue, and it completely shuts down the app's ability to make network requests through Alamofire (because the delegate won't be called ever).
as I said the download and upload called simultaneously on 2 different queues (one of them is usually called on the main thread)
upload example :
Alamofire.upload(.POST, uploadURL,
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: x.dataUsingEncoding(NSUTF8StringEncoding)!, name: "X")
multipartFormData.appendBodyPart(data: fileData, name: "file", fileName: "Y", mimeType: "application/octet-stream")
}
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.response { (request, response, data, error) -> Void in
if let error = error {
callback("Failure", "\(error)")
} else {
callback("SUCCESS", nil)
}
}
case .Failure(let encodingError):
callback(nil, "Failed due to \(encodingError)")
}
}
)
download example :
Alamofire.download(.GET, downloadUrl, parameters: ["a": "a", "b": "b"], destination:
{
tempURL, response in
return path
}).response {
(request, response, _, error) in
let data = NSData(contentsOfURL: path)
doSomeStuffWithDownloadedData(data)
// make another request after download completed
Alamofire.request(.GET, requestUrl, parameters: ["c":"c", "d":"d"]).response {
request, response, data, error in
if let e = error {
log.error("request failed, \(e)")
}
}
}
stack trace
After commenting most of my code I isolated the code causing the problem and it does not related at all to alamofire or NSURLSession.
I have in my own code a call to objc_sync_enter on an array (of objects), it always has a matching objc_sync_exit call on the same array. after changing this call to be on self instead of this array, the deadlock inside NSBlockOperation is gone. It may be related to the fact that an array is not an object but a struct. So if you experience very strange deadlock in your code, I suggest that before you try anything else, make sure you don't have calls of objc_sync_enter on structs.

Resources