Swift webview xcode发布数据 [英] Swift webview xcode post data

查看:91
本文介绍了Swift webview xcode发布数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个webview,目前编码如下:

I have a webview which is currently coded as following:

    let url = NSURL(string: "http://example.com")
    let request = NSURLRequest(URL: url!)

    monitorView.loadRequest(request)

这很好用,但是在向这个网址发布数据然后加载它时我会怎么做?我对swift相当新,似乎无法解决这个问题。

This works just fine, but how would I got about when it comes to posting data towards this url and then loading it? I am fairly new to swift and can't seem to figure this out.

推荐答案

你可以使用像<$ c这样的类$ c> NSURLSession ,它允许控制您的HTTP交互,并在您的webView中加载HTML字符串

You could use a Class like NSURLSession, which allows control over your HTTP interaction, and loads the HTML string in your webView

用法示例:

let request = NSMutableURLRequest(URL: NSURL(string: "http://www.someLink.com/postName.php"))
request.HTTPMethod = "POST"
let postString = "id=XYZ"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in

    if error != nil {
        println("error=\(error)")
        return
    }

    println("response = \(response)")

    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("responseString = \(responseString)")
}
task.resume()

或者您可以使用POST准备 NSMutableURLRequest webView中的正文和负载如下:

Or you can prepare an NSMutableURLRequest with a POST body and load that in your webView like so:

//need to use MutableRequest to set HTTPMethod to Post.
var url = NSURL(string: "http://www.somesite.com/post.php")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
var bodyData: String = "someUsernameOrKey"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
webView.loadRequest(request)

这篇关于Swift webview xcode发布数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆