Networking with NSURLSession

1. App Transport Security

  • Protecting Customer Data

  • What is App Transport Security (ATS)?
    • Disallows cleartext HTTP URL loads
    • Encourages best practice secure connections
    • Defaults to stronger security
    • Allows configuration via app's Info.plist
NSAppTransportSecurity
    NSExceptionDomains
      "example.com"
        NSIncludesSubdomains = YES
        NSExceptionRequiresForwardSecrecy = NO 
        NSExceptionMinimumTLSVersion = "TLSv1.1"

NSAppTransportSecurity
  NSExceptionDomains
   "media.example.com"
     NSExceptionAllowsInsecureHTTPLoads = YES

NSAppTransportSecurity
   NSAllowsArbitraryLoads = YES

NSAppTransportSecurity NSAllowsArbitraryLoads
NSExceptionDomains
   "secure.example.com"
     NSExceptionAllowsInsecureHTTPLoads = NO
  • Configuring ATS

  • Diagnosing issues

    • Active when you build your app for iOS 9 and OS X El Capitan
    • "http://" to "https://" is automatic
    • Use NSAllowsArbitrary Loads for quick triage
    • Log NSURLSession errors
    • CFNETWORK_DIAGNOSTICS=1
  • Protecting Customer Data

  • Next steps

    • Use HTTPS for new projects
    • Transition existing apps from HTTP to HTTPS
    • Use exceptions where needed

2. New Protocol Support in NSURLSession

  • HTTP/2

    • Adoption on the client
    • NSURLSession supports HTTP/2 protocol automatically
    • No source code changes needed
let sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: sessionConfig)
let url = NSURL(string: "https://www.example.com")!
let task = session.dataTaskWithURL(url) {
     (data: NSData?, response: NSURLResponse?, error: NSError?) in 
        ...
}task?.resume()

3. API Changes

  • NSURLConnection

  • Deprecated in OS X 10.11 and iOS 9.0

    • Not going away, apps using it will still work
    • New features will be added to NSURLSession
  • Not supported on watchOS

  • Switching to NSURLSession is easy

  • Switching to NSURLSession

    let queue: NSOperationQueue = ...
    let url = NSURL(string: "https://www.example.com")!
    let request = NSURLRequest(URL: url)
    NSURLConnection.sendAsynchronousRequest(request, queue: queue) { 
      (response: NSURLResponse?, data: NSData?, error: NSError?) in 
          ...
    }
    

    let queue: NSOperationQueue = ...
    let url = NSURL(string: "https://www.example.com")!
    let request = NSURLRequest(URL: url)
    NSURLConnection.sendAsynchronousRequest(request, queue: queue) {
    (response: NSURLResponse?, data: NSData?, error: NSError?) in
    ...
    }
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    (data: NSData?, response: NSURLResponse?, error: NSError?) in
    ...
    }
    task?.resume()

4. New NSURLSession API

  • Sharing Cookies

  • Between Apps and Extensions
    • Apps and their extensions have different cookie storages by default
    • Can use application groups to get a shared data containerOS X 10.11 and iOS 9 introduce new API to create a shared cookie storage

5. New NSHTTPCookieStorage API

let ident = "group.mycompany.mygroupname"let cookieStorage =  NSHTTPCookieStorage.sharedCookieStorageForGroupContainerIdentifier( identifier: ident)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()config.HTTPCookieStorage = cookieStorage
let session = NSURLSession(configuration: config)

6. NSURLSessionStreamTask

  • Asynchronous read

    let task = NSURLSession.sharedSession().streamTaskWithHostName("chat.example.com", port: 5555)!
    task.resume()
    task.readDataOfMinLength(16384, maxLength:65536, timeout: 30.0) {
     (data: NSData?, eof: Bool, error: NSError?) in
      ...
     }
    
    let task = NSURLSession.sharedSession().streamTaskWithHostName("chat.example.com", port: 5555)!
    task.resume()
    let data: NSData = ...task.writeData(data, timeout: 30.0) { (error: NSError?) in
      ...
    }
    
  • Enabling TLS

    let task = NSURLSession.sharedSession().streamTaskWithHostName("chat.example.com", port: 5555)!
    task.startSecureConnection()
    task.resume()
    let data: NSData = ...task.writeData(data, timeout: 30.0) { (error: NSError?) in
      ...
    }
    
  • NSStream support

    let streamTask: NSURLSessionStreamTask = ...
    streamTask.captureStreams()
    
  • NSStream support

    func URLSession(session: NSURLSession,streamTask: NSURLSessionStreamTask, didBecomeInputStream inputStream: NSInputStream, outputStream: NSOutputStream) {
    // Can pass inputStream / outputStream to APIs that consume NSStreams
    }
    
  • Other (informational) delegate methods

    optional func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTask streamTask: NSURLSessionStreamTask)
    
  • Other (informational) delegate methods

    optional func URLSession(session: NSURLSession, betterRouteDiscoveredForStreamTaskstreamTask: NSURLSessionStreamTask)
    optional func URLSession(session: NSURLSession, readClosedForStreamTask streamTask:NSURLSessionStreamTask)
    optional func URLSession(session: NSURLSession, writeClosedForStreamTask streamTask:NSURLSessionStreamTask)
    
  • DataTask conversion

    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
       completionHandler(.BecomeStream)
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeStreamTask streamTask: NSURLSessionStreamTask) {
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末糙捺,一起剝皮案震驚了整個(gè)濱河市舀透,隨后出現(xiàn)的幾起案子互捌,更是在濱河造成了極大的恐慌靶橱,老刑警劉巖国拇,帶你破解...
    沈念sama閱讀 219,490評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異山憨,居然都是意外死亡拜轨,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,581評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門祥得,熙熙樓的掌柜王于貴愁眉苦臉地迎上來兔沃,“玉大人,你說我怎么就攤上這事级及∑故瑁” “怎么了?”我有些...
    開封第一講書人閱讀 165,830評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵饮焦,是天一觀的道長怕吴。 經(jīng)常有香客問我窍侧,道長,這世上最難降的妖魔是什么转绷? 我笑而不...
    開封第一講書人閱讀 58,957評(píng)論 1 295
  • 正文 為了忘掉前任伟件,我火速辦了婚禮,結(jié)果婚禮上议经,老公的妹妹穿的比我還像新娘斧账。我一直安慰自己,他們只是感情好煞肾,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,974評(píng)論 6 393
  • 文/花漫 我一把揭開白布咧织。 她就那樣靜靜地躺著,像睡著了一般扯旷。 火紅的嫁衣襯著肌膚如雪拯爽。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,754評(píng)論 1 307
  • 那天钧忽,我揣著相機(jī)與錄音毯炮,去河邊找鬼。 笑死耸黑,一個(gè)胖子當(dāng)著我的面吹牛桃煎,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播大刊,決...
    沈念sama閱讀 40,464評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼为迈,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼!你這毒婦竟也來了缺菌?” 一聲冷哼從身側(cè)響起葫辐,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎伴郁,沒想到半個(gè)月后耿战,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,847評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡焊傅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,995評(píng)論 3 338
  • 正文 我和宋清朗相戀三年剂陡,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片狐胎。...
    茶點(diǎn)故事閱讀 40,137評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡鸭栖,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出握巢,到底是詐尸還是另有隱情晕鹊,我是刑警寧澤,帶...
    沈念sama閱讀 35,819評(píng)論 5 346
  • 正文 年R本政府宣布,位于F島的核電站捏题,受9級(jí)特大地震影響玻褪,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜公荧,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,482評(píng)論 3 331
  • 文/蒙蒙 一带射、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧循狰,春花似錦窟社、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,023評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至程腹,卻和暖如春匣吊,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背寸潦。 一陣腳步聲響...
    開封第一講書人閱讀 33,149評(píng)論 1 272
  • 我被黑心中介騙來泰國打工色鸳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人见转。 一個(gè)月前我還...
    沈念sama閱讀 48,409評(píng)論 3 373
  • 正文 我出身青樓命雀,卻偏偏與公主長得像,于是被迫代替她去往敵國和親斩箫。 傳聞我的和親對(duì)象是個(gè)殘疾皇子吏砂,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,086評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容