Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active August 16, 2016 04:47
Show Gist options
  • Save KentarouKanno/e5d39c87ca851f7035c1c36fb4c5a9b9 to your computer and use it in GitHub Desktop.
Save KentarouKanno/e5d39c87ca851f7035c1c36fb4c5a9b9 to your computer and use it in GitHub Desktop.
NSURLSession2

NSURLSession2

タスク 説明 Background 対応Delegate
NSURLSessionTask 基底クラス - NSURLSessionTaskDelegate
NSURLSessionDataTask NSDataオブジェクトを使用してデータを送受信します。 データタスクは、多くの場合はインタラクティブな、アプリケーションから サーバーへの短いリクエストを対象としています。 データタスクは、データの各部分が受信され後に一度に一部分ずつ、 または完了ハンドラによって一括して、アプリケーションにデータを 返すことができます。 NSURLSessionTaskDelegate
NSURLSessionUploadTask アップロードタスクはファイル形式でデータを アップロードします。 NSURLSessionTaskDelegate
NSURLSessionDownloadTask ダウンロードタスクはファイル形式でデータを ダウンロードします。 NSURLSessionTaskDelegate NSURLSessionDownloadTask

ATS
info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

★ GET

let urlString = "http://httpbin.org/get"

let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)
request.HTTPMethod = "GET"

let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { data, response, error in
    
    if let data = data, response = response {
        
        print("AllHeader = ",(response as! NSHTTPURLResponse).allHeaderFields)
        print("Data = ",NSString(data: data, encoding: NSUTF8StringEncoding))
    }
})
task.resume()

★ BundleのcsvファイルをPOST Upload
※ uploadTaskWithRequestを使用(NSDataを設定)

let csvFile = NSBundle.mainBundle().pathForResource("data", ofType: "csv")
let csvData = NSData(contentsOfFile: csvFile!)

let url = NSURL(string: "http://localhost:80/upload.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"

let session = NSURLSession.sharedSession()
let tasK = session.uploadTaskWithRequest(request, fromData: csvData) { (data, response, error) in
    
    if let error = error {
        print(error.description)
    }
}
tasK.resume()
<?php
$csv = file_get_contents("php://input");
file_put_contents('data.csv',$csv);
?>

★ BundleのcsvファイルをPOST Upload
※ dataTaskWithRequestを使用(HTTPBodyに設定)

let csvFile = NSBundle.mainBundle().pathForResource("data", ofType: "csv")
let csvData = NSData(contentsOfFile: csvFile!)

let url = NSURL(string: "http://localhost:80/upload.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody   = csvData

let session = NSURLSession.sharedSession()
let tasK = session.dataTaskWithRequest(request) { (data, response, error) in
    
    if let error = error {
        print(error.description)
    }
}
tasK.resume()

★ BundleのcsvファイルをPOST Upload
※ uploadTaskWithRequestを使用(NSURLでファイルを設定)

let csvURL = NSBundle.mainBundle().URLForResource("data", withExtension: "csv")!

let url = NSURL(string: "http://localhost:80/upload.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"

let session = NSURLSession.sharedSession()
let task = session.uploadTaskWithRequest(request, fromFile: csvURL) { (data, response, error) in
    
    if let error = error {
        print(error.description)
    }
}
task.resume()

Basic Auth

★ POST Basic Auth

let url = NSURL(string: "http://localhost:80/upload.php")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"

let str = "data=送信完了"
let strData = str.dataUsingEncoding(NSUTF8StringEncoding)

// Basic認証の設定
let username = "userid"
let password = "pass"
let authStr = "\(username):\(password)"
let data = authStr.dataUsingEncoding(NSUTF8StringEncoding)
let authData = data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
let authValue = "Basic \(authData)"
request.setValue(authValue, forHTTPHeaderField: "Authorization")

request.HTTPBody = strData
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
request.timeoutInterval = 10.0

let session = NSURLSession.sharedSession()
let tasK = session.dataTaskWithRequest(request) { (data, response, error) in
    
    if let data = data, response = response {
        
        print("AllHeader = ",(response as! NSHTTPURLResponse).allHeaderFields)
        print("Data = ",NSString(data: data, encoding: NSUTF8StringEncoding))
    }
    
    if let error = error {
        print(error.description)
    }
}
tasK.resume()

★ GET Basic Auth
参考URL: ベーシック認証をURLに直接書く

Background Fetch

info.plist

<key>UIBackgroundModes</key>
<array>
	<string>fetch</string>
</array>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment