How to load local html file in alamofire? - ios

I'm currently making a web application and need to load a local index.html file as the url, but i'm kinda lost. I'm familiar with the loadHTMLString from WebKit, but kinda lost when using alamofire.
I've tried to loadHTMLString in WebKit with webView with great
func registerShift() {
let url = Bundle.main.url(forResource: "index", withExtension: "html")!
let parameters = [
"brugernavn": "user#email.dk",
"password": "testPass"
]
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
switch response.result {
case .success:
if let value = response.result.value {
print(value)
}
case .failure(let error):
print(error)
}
}
}
I expected the website to actually submit the form, however instead it printes the HTML of the local index.html. The local index.html file is just a simple form containing input (name = brugernavn) and input (name = password).

Related

Failed response from **Alamofire** in swift 5

I'm using Alamofire class for api calling. Api is working properly in Postman
please check below two screenshots for reference,
in first image data is passing inside raw body
in second image data is passing inside Headers field
now i'm using this code to call API
//for params i'm sending below parameters
//["phoneNumber":"911234567890", "countryCode" : "91"]
let headers: HTTPHeaders = [
"deviceId" : deviceId,
"osVersion": osVersion,
"deviceType": deviceType,
"resolution":resolution,
"buildNumber":buildNumber]
AF.request(strURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers:headers).responseData { (response) in
switch response.result {
case .success(let data):
do {
//let asJSON = try JSONSerialization.jsonObject(with: data)
let asJSON = try JSONSerialization.jsonObject(with: data, options: [.fragmentsAllowed])
// success
print(asJSON)
let res : NSDictionary = (asJSON as AnyObject) as! NSDictionary
successBlock(res)
} catch { // error
print("decoding error:\n\(error)")
}
case .failure(let error):
print(error)
failure(error)
}
}
in all other project above code is working fine for api calling, but here i'm getting below error
{ code = 500; data = ""; message = "Failed to convert value of type 'java.lang.String' to required type 'java.util.Locale'; nested exception is java.lang.IllegalArgumentException: Locale part "en;q=1.0" contains invalid characters"; …………………… NamedValueMethodArgumentResolver.java:125)\n\t... 97 more\n"; status = "INTERNAL_SERVER_ERROR"; timestamp = "01-03-2022 07:55:20"; }
i've try several methods like URLEncoding.default, passing custom header, create custom raw request & passed header inside but nothing works,
AnyOne have solution for this issue?
Thanks in Advance.
As it is throwing error related to Local, I think some language is defined and it doesn't accept * for Accept-Language header, try sending "en" in the header Accept-Language.
Check subtags for language:
http://www.iana.org/assignments/language-subtag-registry/language-subtag-registry :
Test Code:
func callAPI() {
let params: Parameters = ["phoneNumber":"911234567890", "countryCode" : "91"]
let headers = [
"deviceId" : "jdhcbkerfjkr",
"osVersion": "3.2.3",
"deviceType": "ANDROID",
"resolution": "122x122",
"buildNumber": "3.2.1",
"Accept-Language": "en"]
AF.request("[Test-URL]",
method: .post,
parameters: params,
encoding: JSONEncoding.default,
headers: HTTPHeaders.init(headers)).response { response in
print(String(data: response.data!, encoding: .utf8)!)
}
}

How to prevent alamofire to put "&" sign to front of parameter

I'm a beginner in Swift. I'm trying to create an application using PUBG api. I add my headers using Alamofire. I have a text field on my storyboard , I enter my nickname there and get the data from pubg api. My problem is Alamofire adds "&" sign to front of parameters so this crashes the url. How can I prevent Alamofire to put "&" sign to parameter?
let playerURL = "https://api.pubg.com/shards/pc-eu/players?filter[playerNames]"
func findPlayer(playerName:String){
let httpParameters : Parameters = ["":playerName]
Alamofire.request(playerURL,method:.get,parameters:httpParameters,encoding:URLEncoding.default,headers:httpHeaders).responseJSON{response in switch response.result{
case .success(let value):
let response = JSON(value)
print(response["data"])
case .failure(_):
return
}
}
}
URL should be like this:
https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PlayerName
Instead it becomes this:
https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D&=PlayerName
If you're using Alamofire to encode the parameters, then you need to let it encode the parameters:
let playerURL = "https://api.pubg.com/shards/pc-eu/players"
....
let httpParameters : Parameters = ["filter[playerNames]": playerName]
...
My entire test case is as follows:
Create a blank one-view project
In AppDelegate add:
let playerURL = "https://api.pubg.com/shards/pc-eu/players"
func findPlayer(playerName:String){
let httpParameters : Parameters = ["filter[playerNames]": playerName]
let request = Alamofire.request(playerURL,
method:.get,
parameters:httpParameters)
print(request)
}
In application(_:didFinishLaunchingWithOptions:) add:
findPlayer(playerName: "PLAYERNAME")
Run
Output:
GET https://api.pubg.com/shards/pc-eu/players?filter%5BplayerNames%5D=PLAYERNAME

Alamofire extra argument 'method' in call from Alamofire example

I would like to state that I've tried every single example and scanned the plethora of other questions exactly like mine to no avail, so I have NO CHOICE but to post.
Xcode: 8.3.1 (8E1000a)
Apple Swift version 3.1 (swiftlang-802.0.51 clang-802.0.41)
Target: x86_64-apple-macosx10.9
OSX 10.12.4
Please see the code:
Note: This is embedded in a function, the parameters "email" and "password" are strings and are available, I also tried setting static string values.
let url = URL(string: "http://website.what.com/api/v1/login")
let params: Parameters = ["email": email, "password":password]
// This Works
Alamofire.request(url!, method: .post, parameters: params)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
// This one returns: "Extra argument Method in call"
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success:
print(response)
case .failure(let error):
print(error)
}
}
The primary I am confident in posting again - the second example was taken straight from the Alamofire github README.
If I am missing something - as in incorrectly encoding a parameter (which I copied directly from Alamofire's github page) or something.
Alternately, if someone can provide me a working sample on Swift 3.1 which allows me to use JSON, Headers, and POST Method.
The first "working" method does not have headers, I am not sure if I can use that example with additional parameters or not?
Sorry for the trouble, very very fresh swift learner who is diving head-first into a complicated world.

iOS Swift uploading PDF file with Alamofire (Multipart)

I'm currently developing an application using iOS 10 and Swift 3 and Alamofire 4
The purpose of this application is to upload a PDF file generated previously.
The PDF generation is working perfectly and the file is created.
However the upload doesn’t work…
I received a success response but the file is not uploaded.
My server response
Multi part Content-Type => multipart/form-data; boundary=alamofire.boundary.56958be35bdb49cb
Multi part Content-Length => 293107
Multi part Content-Boundary => alamofire.boundary.56958be35bdb49cb
responses
SUCCESS: {
uploadedFiles = (
{
details = " Key=Content-Disposition - values=[form-data; name=\"pdfDocuments\"] length=8";
storedFileName = "/var/www/pdf/17/009/22/TMP104150531290406.tmp";
type = PDF;
uploadedDate = 1483999296701;
uploadedFileName = UnknownFile;
}
);
}
end responses
I’m using multi-part to upload my file as Data as you can see here
File url is fine.
I have searched on SO but didn’t find any solution working…
Here you can see my Controller
Alamofire.upload(
multipartFormData: {
multipartFormData in
if let urlString = urlBase2 {
let pdfData = try! Data(contentsOf: urlString.asURL())
var data : Data = pdfData
multipartFormData.append(data as Data, withName:"test.pdf", mimeType:"application/pdf")
for (key, value) in body {
multipartFormData.append(((value as? String)?.data(using: .utf8))!, withName: key)
}
print("Multi part Content -Type")
print(multipartFormData.contentType)
print("Multi part FIN ")
print("Multi part Content-Length")
print(multipartFormData.contentLength)
print("Multi part Content-Boundary")
print(multipartFormData.boundary)
}
},
to: url,
method: .post,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseJSON { response in
print(" responses ")
print(response)
print("end responses")
onCompletion(true, "Something bad happen...", 200)
}
case .failure(let encodingError):
print(encodingError)
onCompletion(false, "Something bad happen...", 200)
}
})
Thanks in advance for the help.
Regards
I have just found my solution to fix this bug.
I have forgot a parameter for the file name.
multipartFormData.append(pdfData, withName: "pdfDocuments", fileName: namePDF, mimeType:"application/pdf")
Thanks for the help.

Getting token from an asp.net web api in iOS / swift

I am a .net developer but very new to iOS and swift development, just need help with consuming Web API using Swift2
The Asp.net Web API has been built with OAuth2 authentication, published to my Azure VM server with SSL certificate installed. The API site itself works properly, tested through Postman
However I got stuck when started writing first few lines of code in Swift trying to get Authentication token. After reading some online tutorials I decided to engage Alamofire, and produced below codes snippet:
func GetToken() {
let params = [
"grant_type" : "password",
"username" : "123456#qq.com",
"password" : "averygoodpassword"
]
let headers = [
"Content-Type" : "application/x-www-form-urlencoded"
]
request(.POST, "https://api.example.com/token",
parameters: params,
headers: headers,
encoding: .JSON)
.responseJSON { request, response, result in
print (request)
print (response?.description)
print (result)
switch result {
case .Success(let JSON):
print("Success with JSON: \(JSON)")
case .Failure(let data, let error):
print("Request failed with error: \(error)")
if let data = data {
print("Response data: \(NSString(data: data, encoding: NSUTF8StringEncoding)!)")
}
}
}
}
It ends up with below output in Xcode which didn't seem to be OK. The error = unsupported_grant_type told me that the request were sent to server but the parameters were not sent with request properly. I really cannot figure out the reason and solution, had been digging on Internet for a few days but still feeling desperate with it. Can anyone help please? Even if someone can provide a pure swift solution without any 3rd party library will be greatly helpful. Thanks!
Xcode output:
Optional( { URL: https://api.example.com/token })
Optional(" { URL: https://api.example.com/token } { status code: 400, headers {\n \"Access-Control-Allow-Headers\" = \"Content-Type\";\n \"Access-Control-Allow-Methods\" = \"GET, POST, PUT, DELETE, OPTIONS\";\n \"Access-Control-Allow-Origin\" = \"*\";\n \"Cache-Control\" = \"no-cache\";\n \"Content-Length\" = 34;\n \"Content-Type\" = \"application/json;charset=UTF-8\";\n Date = \"Fri, 30 Sep 2016 10:30:31 GMT\";\n Expires = \"-1\";\n Pragma = \"no-cache\";\n Server = \"Microsoft-IIS/8.5\";\n \"X-Powered-By\" = \"ASP.NET\";\n} }")
SUCCESS
Success with JSON: {
error = "unsupported_grant_type";
}
I had a similar problem trying to POST to MailGun for some automated emails I was implementing in an app.
I was able to get this working properly with a large HTTP response. I put the full path into Keys.plist so that I can upload my code to github and broke out some of the arguments into variables so I can have them programmatically set later down the road.
// Email the FBO with desired information
// Parse our Keys.plist so we can use our path
var keys: NSDictionary?
if let path = NSBundle.mainBundle().pathForResource("Keys", ofType: "plist") {
keys = NSDictionary(contentsOfFile: path)
}
if let dict = keys {
// variablize our https path with API key, recipient and message text
let mailgunAPIPath = dict["mailgunAPIPath"] as? String
let emailRecipient = "bar#foo.com"
let emailMessage = "Testing%20email%20sender%20variables"
// Create a session and fill it with our request
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: NSURL(string: mailgunAPIPath! + "from=FBOGo%20Reservation%20%3Cscheduler#<my domain>.com%3E&to=reservations#<my domain>.com&to=\(emailRecipient)&subject=A%20New%20Reservation%21&text=\(emailMessage)")!)
// POST and report back with any errors and response codes
request.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let error = error {
print(error)
}
if let response = response {
print("url = \(response.URL!)")
print("response = \(response)")
let httpResponse = response as! NSHTTPURLResponse
print("response code = \(httpResponse.statusCode)")
}
})
task.resume()
}
The Mailgun Path is in Keys.plist as a string called mailgunAPIPath with the value:
https://API:key-<my key>#api.mailgun.net/v3/<my domain>.com/messages?
I'm slightly opposed to using 3rd party libraries, especially for small things like a http POST and this seems like a much more maintainable solution to me. Anyways, hope this helps, let me know if you have any questions!

Resources