Dennis Smink
Dennis Smink

Reputation: 450

Swift webview xcode post data

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)

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.

Upvotes: 2

Views: 5837

Answers (2)

Woodstock
Woodstock

Reputation: 22926

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

Usage example:

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()

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)

Upvotes: 8

HannahCarney
HannahCarney

Reputation: 3631

I really like AFNetworking

GET

import AFNetworking

var urlBase = "www.example.com"

func getShopData(shopDataResponse:(Bool)-> Void )
{
        if let userid = @"exampleid"
        {
        let urlStr =  urlBase + "shops/get?u=" + (userid as! String)
        let manager = AFHTTPRequestOperationManager() 
        manager.GET(urlStr, parameters: nil, success: {(req : AFHTTPRequestOperation!, result : AnyObject!) in
            println("The Result \(result)")
            if let resultActual: AnyObject = result
            {
              println(result)
              shopDataResponse(true);
            }

            , failure: {(req : AFHTTPRequestOperation!, error : NSError!) in
                println("fail with error \(error.description)")
                shopDataResponse(false);
        })
    }
 }

POST

func getName(id :String){
    let manager = AFHTTPRequestOperationManager()
    let urlStr = urlBase + "name"
    let userId = id
        manager.requestSerializer = AFJSONRequestSerializer()
        manager.POST(urlStr, parameters: parameters,
            success: {(req : AFHTTPRequestOperation!, result : AnyObject!) in
                println("JSON: \(result)")
            }
            , failure: {(req : AFHTTPRequestOperation!, error : NSError!) in
                println("fail with error \(error.description)")
        })
    }

}

Upvotes: 0

Related Questions