I want to open an url in the background to update my database with information,
but it should not open safari because customer shouldn't be able to see the php link.
would be glad for any help,
i just need help to open the URL in the background
I believe what you're looking for is an HTTP request. This is what browsers do to get content from a webpage. There are many ways to do an HTTP request to a url in iOS. One such way is with the URLSession class.
let url = URL(string: "http://www.google.com/") //Or your URL
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = "Data to send to your backend".data(using: .utf8)!
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
//There was an error
} else {
//The HTTP request was successful
print(String(data: data!, encoding: .utf8)!)
}
}
task.resume()
This will send the data in the httpBody property to your backend in a HTTP request.
Related
I'm trying to get HTML data from a website using swift to parse some tournament-results within an iPhone app.
However if I'm trying to access the site inside the code I get redirected to a page where normally you have to accept cookies.
I know that this cookie is stored in the HTTPCookieStorage but I can't seem to find a way to send it with my URLRequest. No matter what I do I always get the contents of the cookie-site instead of the page I'm trying to get.
Here is my approach:
let cookies = HTTPCookieStorage.shared.cookies! as [HTTPCookie]
var cookie = [HTTPCookie]()
for i in cookies {
if i.domain == "www.turnier.de" {
cookie.append(i)
}
}
HTTPCookieStorage.shared.setCookies(cookie, for: URL(string: "https://www.turnier.de/sport/winners.aspx?id=44325544-0A05-4330-BC8D-114AB3ECD25D"), mainDocumentURL: URL(string: "https://www.turnier.de/sport/winners.aspx?id=44325544-0A05-4330-BC8D-114AB3ECD25D"))
var request = URLRequest(url: URL(string: "https://www.turnier.de/sport/winners.aspx?id=44325544-0A05-4330-BC8D-114AB3ECD25D")!)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
let responseString = String(data: data!, encoding: .utf8)
print(responseString)
}
task.resume()
I'm trying to make a POST call in my app using URLSession (and AlamoFire) no luck with either, I'm checking the network call on Charles Proxy and it's always being sent as a GET call even though I've specified the HTTPMethod to be "POST" or .post in both.
Weirdest part is updating the call to "DELETE" or "PUT" will work...just not "POST" or .post
I've tried just building the request from ground up in URLSession instead of using AlamoFire, tried changing the HTTPMethod (which works, just not for POST)
let session = URLSession.shared
let url = URL(string: endpointURL)!
var request = URLRequest(url: url)
request.httpMethod = "POST"
let jsonData: Data = try! requestProto.serializedData()
let task = session.uploadTask(with: request, from: jsonData) { data, response, error in
print("request made")
}
task.resume()
Expected: Charles records a POST call
Actual: Charles is recording GET call for both GET and POST calls, but DELETE and PUT are working fine.
Try this with URLSession
// create a `URLRequest` because post are urlRequest used with urlSession.shared.uploadTask
var request = URLRequest(url: url)
// here pass in data format the body of the request
request.httpBody = body
// the request method.
request.httpMethod = "post"
// required when send a json type in request
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
URLSession.shared.uploadTask(with: request, from: nil) { (data, response, error) in
let response = (response as? HTTPURLResponse)?.statusCode
if (response! == 500 ){
print("error")
}
print("request made")
}.resume()
I don't know why, but make sure that you are sending https request (not http).
I am trying to send a HTTP "POST" request for a web-service that should return a base64 encoded picture. This is an example HTTP request for the service:
I am trying the following:
func fetchPicture(username: String, password: String) {
let url = URL(string: "https://myurl.com/download/bootcamp/image.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.setValue(password.stringToSHA1Hash(), forHTTPHeaderField: "Authorization")
let postString = "username=\(username)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
}
I am getting an error 401 Unauthorized, I don't actually know whether it is because my request is bad all together or just the login initials. It would be grand if someone could go over the code and tell me if it actually corresponds to the request example shown above.
Thanks!
The first thing I notice is that you aren’t setting the request HTTP Method:
request.httpMethod = “POST”
As it turns out, I was using the CommonCrypto hashing function wrongly, I ended up using this instead:
https://github.com/apple/swift-package-manager/blob/master/Sources/Basic/SHA256.swift
And the SHA256 hash it returned was the correct one I needed, maybe this might help someone in the future.
I have a php webAPI which works well and I want to login with that in my app. I want to use cookies for that. So, I save the cookies when the user signs in and that works. I store it in userdefaults when I want to use only place cookies into HTTPCookieStorage.shared.
I try to use this for my new request, and my question is how can I add the cookies to my request?
I tried this but it's not working...
let cookiesArray = HTTPCookieStorage.shared.cookies
print(cookiesArray)
//HTTPCookieStorage.shared.setCookies(cookiesArray!, for: url, mainDocumentURL: url)
let headers = HTTPCookie.requestHeaderFields(with: cookiesArray!)
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.httpShouldHandleCookies = true
urlRequest.httpBody = postString.data(using: String.Encoding.utf8)
urlRequest.allHTTPHeaderFields = headers
//urlRequest.setValue("PHPSESSID=oe22uf92poc5c7s23u4ukl83g0", forHTTPHeaderField: "Cookie")
//URLSessionConfiguration().httpCookieAcceptPolicy = .always
let session = URLSession.shared
session.configuration.httpCookieStorage = HTTPCookieStorage.shared
session.configuration.httpCookieAcceptPolicy = .always
session.configuration.httpShouldSetCookies = true
session.configuration.httpAdditionalHeaders = headers
let task = session.dataTask(with: urlRequest) { (data, response, error) in
print(data)
print(response)
print(error)
print("itt az end\n")
}
task.resume()
I can't comment yet, but I agree that more info is needed. If you are getting errors those would be helpful to post. Also, what you are getting for your
data
response
error
would be helpful.
Other than that, I would first look at setting up Charles as an HTTP Proxy so you can see exactly what is happening when you make the request. Knowing what response you are receiving will let you know what is going wrong.
https://www.charlesproxy.com/
I cannot for the life of me figure out this problem. And I hope you guys can.
I want to send a username and a password over a HTTPS POST. Problem is, I cannot make it work.
The code I am trying to make work right now is:
import UIKit
import Foundation
import PlaygroundSupport
let url:URL = URL(string: "https://mywebsite.com/myAPI")!
let session = URLSession.shared
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let paramString = "username=Pleasework&password=itwont"
request.httpBody = paramString.data(using: String.Encoding.utf8)
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let data = data, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = String(data: data, encoding: String.Encoding.utf8)
print(dataString ?? "Got nothing")
}
task.resume()
Looking at my server logs, this request goes through, but it is supposed to create a file containing said params. I tried using a Chrome extension called "Request Maker", and the file was created. (The file is created with PHP, and is irrelevant to this question)I found that the file was only created once the content type was specified, so I tried that in Swift.
I am using Swift 3 and Xcode 8, I hope you guys can help me send a simple post request with a content type to a URL, all of the other answers on Stackoverflow have not helped me.
Thanks