我在应用程序中打开请求时遇到问题。此代码将请求发送到Web视图。我需要在手机的浏览器中打开此请求。我无法打开它或在Web浏览器中进行请求。当我使用命令代码时,只能使用url的字符串格式。我该如何请求????
import UIKit
class PaymentViewController: UIViewController, UIWebViewDelegate {
var delegate: BackProtocol? = nil
var firstCall = true
var providerId: Int!
var transactionId: String!
@IBOutlet weak var webView: UIWebView!
func configureView() {
self.navigationItem.title = LocalizationSystem.sharedInstance.localizedStringForKey(key: "pay" , comment:"")
// back button
self.navigationItem.addCustomButton(style: .action, position: .left, customView: UIView())
if LocalizationSystem.sharedInstance.getLanguage() == "fa" {
self.navigationItem.addBackButtonEnglishLanguage(target: self, selector: #selector(onBackPressed))
} else {
self.navigationItem.addBackButton(target: self, selector: #selector(onBackPressed))
}
self.webView.delegate = self
}
override func viewDidLoad() {
super.viewDidLoad()
self.configureView()
var request = URLRequest(url: URL(string: String(format: "%@%@",
Downloader.API_BASE_URL,
String(format: Downloader.API_PAYMENT_URL, transactionId,
providerId, Statics.CALLBACK_URL)))!)
request.httpMethod = "GET"
request.setValue(UserInfo.acessToken!, forHTTPHeaderField: "Authorization")
self.webView.loadRequest(request)
// guard let url = URL(string: "http://www.google.com") else {
// return //be safe
// }
//
// if #available(iOS 10.0, *) {
// UIApplication.shared.open(url, options: [:], completionHandler: nil)
// } else {
// UIApplication.shared.openURL(url)
// }
}
func webViewDidFinishLoad(_ webView: UIWebView) {
if let requestedUrl = webView.request?.mainDocumentURL?.absoluteString {
let parts = requestedUrl.components(separatedBy: "/")
// return to previous page
if parts[3] == "verify_payment" {
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) { // 2 seconds later
self.onBackPressed()
}
}
} }
尝试一下:
var request = URLRequest(url: URL(string: "http://www.yourUrl")!)
request.httpMethod = "POST"
let params = "first=xyz&second=abc"
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)
{
self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourUrl.com")!)
}
}
task.resume()
}