I'm trying to send data to a WebAPI service that uses HTTP and not HTTPS, however I get the following error:
"Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value"
Here is my code:
func logSample(emailSKU:String) -> String {
//let myAPI = "https://itunes.apple.com/us/rss/topmovies/limit=25/json"
let myAPI = "http://<myURlHere>/api/xxx"
let url = URL(string: myAPI)
let session = URLSession.shared.dataTask(with: (url)!) { (data, response, error) in <====== Breaks on this line
print("Response was:")
print(response)
}
session.resume()
return "return something here"
}
The API service works just fine from other applications.
If I use the iTunes url above, then everything works fine, so the only difference is the HTTP ver HTTPS.
I have added 'Allow Arbitrary Loads' declaration to the plist, any ideas?
I checked the RFC 3986 and it is the "|" character that isn't allowed and that you need to encode.
To supplement #Joakims answer:
The URL given is invalid because of the use of the | character and needs to be encoded. You can do this in the following way:
let urlString = "http://example.com/api/Scans?emailSKU=fred#example.com|123456"
if let encodedURLString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
let url = URL(string: encodedURLString)
print(url)
}
Which outputs:
Optional(http://example.com/api/Scans?emailSKU=fred#example.com%7C123456)
So | needs to be encoded, which replaces it with %7C
Related
I have a Firebase Cloud Function that I call from a URL rather than a function. The URL is used to load a WKWebView and the function is being called using one of the parameters in the URL, specifically the return_url.
An example of the URL to load the WKWebView would be https://domain.name?app_name=app_name&return_url=cloud_function_url.
private func loadWKWebView() {
let url = "https://domain.name"
let params = "param1=param1&return_url=\(cloud_function_url)"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.httpBody = params.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
if data != nil {
if let returnString = String(data: data!, encoding: .utf8) {
DispatchQueue.main.async {
self.webView.loadHTMLString(returnString, baseURL: URL(string: url)!)
}
}
}
}
task.resume()
}
The URL loads an authentication page in which the user must enter their username and password and returns the parameter I need.
I can console log the parameter but I don’t know how to pass the data to my iOS application because it is not a function “directly” that is making the call to the function expecting the result. The result depends on whether the user enters a valid username and password.
How can I send the response once the user logs in to my app?
What you are putting in params is query parameters. That should be appended to the URL, not sent as data in a POST.
I suggest using a URLComponents struct to compose your URL from the parts you need (probably host plus queryItems.)
I am trying to perform an HTTP POST request in swift that will send some data to my server using PHP file, but it crashes with the error
Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
The token and selectedAreaNames (the error is in the first line) are just regular strings. What could be the problem?
let url = URL(string: "https://xxxxxxx.xxx/register.php/\(token)|\ (selectedAreaNames)")! //error is here...
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error: \(error)")
} else {
if let response = response as? HTTPURLResponse {
print("statusCode: \(response.statusCode)")
}
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("data: \(dataString)")
}
}
}
task.resume()
Assuming that’s really how your URL must look, you can do:
let url = URL(string: "https://xxxxxxx.xxx/register.php")!
.appendingPathComponent(token + "|" + selectedAreasNames)
That will percent escape those portions of the URL (including the |).
That having been said, this is an exceedingly unusual format for a POST request, which usually has the data being posted inside the body of the request, not just added as another path component of the URL. And if this was a GET request, where the parameters are added to the URL, you’d generally see this after a ? in the URL, separating the path of the request from the query. And this structure of simply TOKEN|VALUES is an unusual query structure, too.
I am using an online swift playground to test http post and get request, the post aspect works fine, but when i add the get request,it gives the following error"error: extraneous '}' at top level.
The post code works fine.
// Post method
var url = URL(string: "http://196.46.20.80:8085/fideldesign")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "email=oshinowo_sola#yahoo.ca&amount=15000&description=swift¤cy=566&fee=0&returnurl=http://www.oleronesoftwares.com&secretkey=2BC80A5EB5BB6A64A772F9806A7E9A0B16702043AB475DC4" // which is your parameters
request.httpBody = postString.data(using: .utf8)
//Getting response for POST Method
DispatchQueue.main.async {
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
return // check for fundamental networking error
}
// Getting values from JSON Response
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? NSDictionary
}catch _ {
print ("OOps not good JSON formatted response")
}
}
task.resume()
}
The code is to post dynamic records from user input like email address,amount,description into an external url and then return the get request in json format.
Try closing the project and opening it again.
I was getting this same error and also when I tried pressing Enter (typing newline character) on the line that was problematic (It was the last line in the file for me), Xcode would insert the characters
ker;")
into my editor.
I was getting this error, until I closed and reopened the project, in which these errors went away and the random characters stopped appearing also.
What worked for me was replacing the file.
Create new file, different name than current buggy file.
Copy/paste code into this new file.
Go ahead and delete that file with the error.
..For some reason using the same name transferred over the error, even if I deleted the other file.
I am a beginner, trying to code a POST datarequest to post a vote to the 'rating' field of a Drupalnode (so that users can rate movies). I have followed online guides, carefully copying the syntax, but in Xcode am receiving this error for for this line:
let movieEndpoint: String = https://www.examplesitename.com/film1
The red error message is "consecutive statements on a line must be separated by a ';'
The error highlights the ':' after https, and suggests "fix it" with an ';' but changing it to https;www.examplesitename.com/film1 then brings up another red error 'expected expression' (and doesn't seem correct as it is a URL)
For context, below is my code, (which I hope will work to post my data request but haven't been able to check yet)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
let movieEndpoint: String = https://www.sitename.com/film1
guard let movieURL = NSURL(string: movieEndpoint) else {
print("Error: cannot create URL")
return
}
let movieUrlRequest = NSMutableURLRequest(URL: movieURL)
movieUrlRequest.HTTPMethod = "POST"
let task = session.dataTaskWithRequest(movieUrlRequest, completionHandler:{ _, _, _ in })
let newRating = ["rating": 50, "userId": 1,]
let jsonRating: NSData
do {
jsonRating = try NSJSONSerialization.dataWithJSONObject(newRating, options: [])
movieUrlRequest.HTTPBody = jsonRating
} catch {
print("Error: cannot create JSON from todo")
return
}
movieUrlRequest.HTTPBody = jsonRating
task.resume()
}
Thank you for any help you can give me.
The proper way to declare a String in Swift is to add " " around the string.
Fix your code like this:
let movieEndpoint: String = "https://www.sitename.com/film1"
My url Request is like "http://www.heriam.com/gms.setvalue%20dim100%"
and i use Alamofire for the Request
Tha APP chrashed with fatal error: unexpextendly found nil while unwrapping an Optional Value
Alamofire.request(.GET, "http://www.heriam.com/gms.setvalue%20dim100%")
.authenticate(usingCredential: credential)
.response {(request, response,string, error) in
println(response)
}
The problem is the last %! If i leave it all is fine an the Request works.
do you have an idea sending a Request ending with an %???
You have to prepare your link before converting it to url using stringByAddingPercentEscapesUsingEncoding. Besides that NSURL method might return nil so you should use if let to unwrap the optional result as follow:
let link = "http://www.heriam.com/gms.setvalue%20dim100%"
if let linkWithPercentEscape = link.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
if let url = NSURL(string: linkWithPercentEscape) {
println(url)
}
}