LoginSignup
12
11

More than 5 years have passed since last update.

Swift2.0 POST送信とBasic認証

Last updated at Posted at 2015-11-09

こちらを参考に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']; 
?>
12
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11