こちらを参考にSwift2.0に書き換えました。
Basic認証も追加しています。
ViewController.swift
import UIKit
class ViewController: UIViewController{
var myConfig:NSURLSessionConfiguration!
override func viewDidLoad() {
super.viewDidLoad()
let str = "data=送信完了"
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)
let url = NSURL(string:"http://hogehoge.com/post.php")
let request = NSMutableURLRequest(URL: url!)
// Basic認証の設定
let username = "ユーザ名"
let password = "パスワード"
let authStr = "\(username):\(password)"
let data = authStr.dataUsingEncoding(NSUTF8StringEncoding)
let authData = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
let authValue = "Basic \(authData)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")
request.HTTPMethod = "POST"
request.HTTPBody = strData
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0
var response: NSURLResponse?
do {
let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: &response)
let myData:NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
print(myData)
} catch (let e) {
print(e)
}
}
}
任意(hogehoge.com/post.php)のサイトにPHPを設置
post.php
<?php
echo $_POST['data'];
?>