Perform POST request in Swift

I am trying to do something like this:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];

request.HTTPMethod = @"POST";

NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];

This is what I have so far:

  • Capture Wi-Fi network changing event in iOS
  • UICollection View causes “UICollectionViewFlowLayoutBreakForInvalidSizes” on smaller devices
  • Reload storyboard to change locale
  • Parse and GMaps iOS SDK incompatibility in Swift?
  • How to still use iOS6 UI in iOS 7?
  • How to animate images using bitmaps / rgb data in iOS
  • var url = NSURL(string: "some url")
    var request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    
    var dataString = "some data"
    var requestBodyData: NSData = dataString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) as NSData
    
    request.HTTPBody = requestBodyData
    
    var connection = NSURLConnection(request: request, delegate: self, startImmediately: false)
    
    println("sending request...")
    
    connection.start()
    

    However, the var requestBodyData: line throws the first stone with “Cannot convert the expression’s type NSData to type NSData”

    Anyone care to weigh in?

    2 Solutions Collect From Internet About “Perform POST request in Swift”

    stringByAddingPercentEscapesUsingEncoding returns a string instead of an NSData object. According to this answer, you need to use this to convert to an NSData instance:

    let data = (anySwiftString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
    

    Using Alamofire to send HTTP POST request

    let request = NSMutableURLRequest(URL: NSURL(string: "https://www.google.com")!)
    request.HTTPMethod = "POST"
    
    let body = "email=\(email)&access_token=\(token)"
    request.HTTPBody = body.dataUsingEncoding(NSUTF8StringEncoding)
    
    Alamofire.request(request).responseJSON { response in
    
            NSLog("response.request: \(response.request)")  // original URL request
            NSLog("esponse.response: \(response.response)") // URL response
    
            switch response.result {
            case .Success:
                NSLog("Validation Successful")
            case .Failure(let error):
                // Logout
                NSLog("\(error), \(String(data: response.data!, encoding: NSUTF8StringEncoding))")
                return
            }
    
            // Save sip account information to NSUserdefaults
            if let json = response.result.value as? [String: AnyObject]{
                // Do your stuff
            } 
    }