Please Notice: Not A Duplicate
Please learn all of this, earlier than you resolve my query is a replica, as a result of I’ve looked for solutions and skim quite a few on SO, however none of them deal with the difficulty of getting [FromForm]
WebAPI binding.
I’ve the next WebAPI methodology in a Controller:
[HttpPost("SetScreenName")]
public ActionResult SetScreenName([FromForm] String guid, [FromForm] String screenName)
The consumer can merely move in a guid and a screenName to set the screenName for the consumer profile.
I can name this simply from JavaScript fetch
utilizing the next code:
const formDataX = new FormData();
formDataX.append("guid","fakeguid-here");
formDataX.append("screenName", "newoneForTest");
fetch("https://localhost:7103/Consumer/SetScreenName", {
methodology: 'POST',
physique: formDataX,
})
.then(response => response.json())
.then(knowledge => console.log(knowledge));
Now, I must know the best way to make a name to this identical WebAPI methodology utilizing Swift (in a iOS App / SwiftUI)
Here is What I’ve Tried
I have been making an attempt to get through this for a few days and would all the time get errors again from my WebAPI stating that one or each of the parameters (guid, screenName) had been lacking.
Here is an inventory of SO solutions and snippets of code I’ve tried to attract the reply from:
Received the next code which I partially used, however nonetheless failed :
Notice: the failure was all the time that one or each params had been lacking.
let url = URL(string: "https://httpbin.org/put up")!
var request = URLRequest(url: url)
request.setValue("software/x-www-form-urlencoded", forHTTPHeaderField: "Content material-Sort")
request.setValue("software/json", forHTTPHeaderField: "Settle for")
request.httpMethod = "POST"
Tried following code however WebAPI would solely acknowledged the primary param (guid
):
url.append(queryItems: [URLQueryItem(name: "guid", value: "(guid)"), URLQueryItem(name: "screenName", value: "(screenName)")])
Tried to encode the params as JSON utilizing code from that reply:
var outData = userData(uuid.uuidString.lowercased(), screenName)
var je = JSONEncoder()
guard let jsonData = attempt? je.encode(outData) else{
print ("encode FAILURE!")
return false
}
End result knowledge appeared like:
{"guid"="5c290f79-73a2-4bba-b34e-4d68c9d73ff7","screenName"="sallafootam"}
None of those options labored and my WebAPI would all the time point out that a number of params (guid
or screenName
) had been lacking.
What’s the definitive set as much as put up to my WebAPI methodology utilizing Swift?