I am very new to XCODE and iOS and I can't figure out how to do an authentication on IBM Domino server. I am trying to do a simple app to get some data from the server.
This is the latest version of my attempt. Bear in mind, that couldn't find information on what IBM Domino server needs. But I've done tons of authentications with javascript. I've deliberatly left the commented part, which is one of the attempts to do a login.
func doLogin(){
print("entered doLogin")
let myUrl: String = "https://url.com/names?login"
guard let url = URL(string: myUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)else {
print("Error: cannot create URL")
return
}
var request = URLRequest.init(url: url)
request.httpMethod = "POST"
let params = ["Username":String(describing: self.username), "Password":String(describing: self.password)]
request.httpBody = try? JSONSerialization.data(withJSONObject: params, options: [])
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
//URLSession.shared.dataTask(with: request) { (data:Data?, response:URLResponse?, error:Error?) in
// if let safeData = data{
// print("response: \(String(data:safeData, encoding:.utf8))")
// }
//}
//let postString = "Username=\(String(describing: self.username))&Password=\(String(describing: self.password))"
//request.httpBody = postString.data(using:String.Encoding.utf8)
request.timeoutInterval = 30.0
//print(request)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration : configuration)
//let session = URLSession(configuration: configuration, delegate: self as! URLSessionDelegate, delegateQueue: nil)
let task = session.dataTask(with: request) {
(data : Data?, response:URLResponse?, error) in
// check for any errors
guard error == nil else {
print("error calling POST on url")
print(error!)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
print ("responseData:")
print(responseData)
}
}
//print ("response:")
//print(task.response)
task.resume()
Related
I Use Laravel as backend and I have below route to verify the users
$router->post('SignIn','Api\V1\UserProfileController#SignIn');
I have tested this route many time using postman and its working fine, now i want to send post request from my app using below request
let url = URL(string: "http://192.168.xxx.xxx/BARI/public/Api/V1/Verify")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let param : [String : Any] = ["ph_number" : userDefaults.string(forKey: "ph_number")!, "code" : smsNumberTF.text!]
request.httpBody = try? JSONSerialization.data(withJSONObject: param, options: [])
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = TimeInterval(30)
configuration.timeoutIntervalForResource = TimeInterval(30)
let session = URLSession(configuration: configuration)
let task = session.dataTask(with: url) { (data, urlResponse, error) in
if(error != nil){
DispatchQueue.main.async {
self.progress.stopAnimating()
self.isLoading = false
// show connection error alert
print("connection error : \(error?.localizedDescription)")
}
}else{
let outputStr = String(data: data!, encoding: String.Encoding.utf8) as String?
print(outputStr)
DispatchQueue.main.async {
do {
self.progress.stopAnimating()
self.isLoading = false
let jsonData = try JSONDecoder().decode(BasicResponse.self, from: data!)
if(jsonData.statusCode == 1000){
// let userDefaults = UserDefaults.standard
// userDefaults.set("+964" + self.phoneET.text!, forKey: "contact_number")
// let vc = Verfiy()
// self.navigationController?.pushViewController(vc, animated: true)
}else{
//self.alert.show(target: self.view, message: jsonData.message!)
}
}
catch let jsonerr {
print("error serrializing error",jsonerr)
}
}
}
}
task.resume()
But Im getting Method Not Allowed response back? what Im missing her!?
Any Help will be much appreciated
below is my get request code. but getting 403 error ...please help!
func getUser(completion: #escaping(Result<User?, AuthenticationError>)-> Void) {
let loginVM = LoginViewModel()
let token = loginVM.accessToken
guard let url = URL(string: myURL) else {
completion(.failure(.custom(errorMessage: "URL is not correct")))
return
}
var request = URLRequest(url:url)
request.httpMethod = "GET"
request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data, error == nil else {
completion(.failure(.custom(errorMessage: "No data")))
return
}
guard let registerResponse = try? JSONDecoder().decode(User.self, from: data) else{
completion(.failure(.custom(errorMessage: "no response")))
return
}
completion(.success(User))
}.resume()
}
and instruction from my backend guy for this part is this :
I tested on Postman It work as like charm. It must be happen in my request code with Authorization....
I'm just learning Web APIs with Swift.
And I've done as follows
Make some basic configuration
let session = URLSession(configuration: .default)
// Prepare URL #the URL is virtual now
let url = URL(string: "http://something.com/api")
guard let requestUrl = url else { fatalError() }
// Prepare URL Request Object
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
Set Post parameter
let parameters: [String: String] = [
"user_ID": "1",
]
let jsonData = try JSONEncoder().encode(parameters)
request.httpBody = jsonData
Take request to our web api
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
guard let data = data else { return }
do {
let myEnterprise = try JSONDecoder().decode(Enterprise.self, from: data)
print("Response data:\n \(myEnterprise)")
print("Response data:\n \(myEnterprise.returnData)")
} catch let jsonErr {
print(jsonErr)
}
}
task.resume()
myEnterprise is always nil. Can anyone help me?
I'm new to Swift and I am trying to refactor my URL Post requests. I have multiple URL POST requests inside the same View Controller like this. Everything works fine but it seems to me that there is a lot of repetitive code that could be reused. Particularly, I don't know how to pass/handle different Data Models that should be used in parseRequest1 and parseRequest2. I also read that there should be only one session used for URL requests within the same project. Any help would be greatly appreciate it!
func request1() {
let parameters = [...//some parameters to send]
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
self.parseRequest1(data: safeData)
}
}.resume()
}
func parseRequest1(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(DataModelForRequest1.self, from: data)
DispatchQueue.main.async {
self.performAction1(request1Result)
}
} catch {
print(error)
}
}
Then I have another URL request request2 which is almost identical except the parameters, and model to be used for decoding and action inside parseRequest2.
func request2() {
let parameters = [...//some parameters to send]
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
self.parseRequest2(data: safeData)
}
}.resume()
}
func parseRequest2(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(DataModelForRequest2.self, from: data)
DispatchQueue.main.async {
self.performAction2(request2Result)
}
} catch {
print(error)
}
}
The only differences seem to be:
request parameters
type of model returned
the action you do after the response is received
This means that we can write this as one single method taking the above three values as parameters:
func request<T: Codable>(modelType: T.Type, parameters: [String: Any], completion: (T) -> Void) {
func parseResponse(data: Data){
let decoder = JSONDecoder()
do{
let decodedData = try decoder.decode(T.self, from: data)
DispatchQueue.main.async {
completion(decodedData)
}
} catch {
print(error)
}
}
guard let url = URL(string: "https//www.....") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let parametersToSend = try? JSONSerialization.data(withJSONObject: parameters, options: [])
else {
print("Error")
return
}
request.httpBody = parametersToSend
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let safeData = data {
parseResponse(data: safeData)
}
}.resume()
}
You can then call this method with the appropriate parameters as per your needs.
I have done my Post-request but I am unsure about how to make it possible to send a full question and to get the most common answers back to my app.
I am in such a big need of this code in my program so would love to get some examples on how to make it work
Have tried to right the question into the parameters with a "+" instead of space which resulted into nothing.
#IBAction func GetAnswer(_ sender: Any) {
let myUrl = URL(string: "http://www.google.com/search?q=");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
let postString = questionAsked;
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
print("response = \(String(describing: response))")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let answer = parseJSON[" Answer "] as? String
self.AnswerView.text = ("Anwer: \(String(describing: answer))")
}
} catch {
print(error)
}
}
task.resume()
}
You do not use google.com/search, please check the api documentation
Paste following in Playground, should give a good start
struct Constants {
static let apiKey = "YOUR_API_KEY"
static let bundleId = "YOUR_IOS_APP_BUNDLE_ID"
static let searchEngineId = "YOUR_SEARCH_ENGINE_ID"
}
func googleSearch(term: String, callback:#escaping ([(title: String, url: String)]?) -> Void) {
let urlString = String(format: "https://www.googleapis.com/customsearch/v1?q=%#&cx=%#&key=%#", term, Constants.searchEngineId, Constants.apiKey)
let encodedUrl = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)
guard let url = URL(string: encodedUrl ?? urlString) else {
print("invalid url \(urlString)")
return
}
let request = NSMutableURLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10)
request.httpMethod = "GET"
request.setValue(Constants.bundleId, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
let session = URLSession.shared
let datatask = session.dataTask(with: request as URLRequest) { (data, response, error) in
guard
error == nil,
let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String : Any]
else {
// error handing here
callback(nil)
return
}
guard let items = json["items"] as? [[String : Any]], items.count > 0 else {
print("no results")
return
}
callback(items.map { ($0["title"] as! String, $0["formattedUrl"] as! String) })
}
datatask.resume()
}
Usage
googleSearch(term: "George Bush") { results in
print(results ?? [])
}
Create a new search engine using following url
https://cse.google.com/cse/create/new
If you would like search entire web, use following steps
edit your engine using https://cse.google.com/cse/setup/basic?cx=SEARCH_ENGINE_ID
remove any pages listed under Sites to search
turn on Search the entire web