SlideShare a Scribd company logo
1 of 46
Download to read offline
URLProtocol
2017/11/24
Introduction
•
• API
• API
•
#if DEBUG
DispatchQueue.global().async {
//
let user = User.mockData()
//
}
#else
let request = URLRequest(url: URL(string: "https://api.test.com/
users/foo")!)
let task = URLSession.shared.dataTask(with: request) { (data,
response, error) in
//
}
task.resume()
#endif
Demo
"NS" URLProtocol
Swift3 `Foundation` API "NS"
"NS"
URL Loading System
URL Loading System
The URL loading system is a set of classes and
protocols that allow your app to access content
referenced by a URL. At the heart of this
technology is the NSURL class, which lets your
app manipulate URLs and the resources they
refer to.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/
URLLoadingSystem/URLLoadingSystem.html
URL loading system
• ftp://
• http://
• https://
• file:///
• data:
Foundation
• URL
•
•
•
•
•
URLProtocol
URLProtocol
An NSURLProtocol object handles the loading
of protocol-specific URL data. The
NSURLProtocol class itself is an abstract class
that provides the infrastructure for processing
URLs with a specific URL scheme. You create
subclasses for any custom protocols or URL
schemes that your app supports.
https://developer.apple.com/documentation/foundation/urlprotocol
•
•
•
•
•
https://www.raywenderlich.com/76735/using-nsurlprotocol-swift
• URLProtocol
• URLProtocol
registerClass(_:)
• class func canInit(with request: URLRequest) -
> Bool
• class func canonicalRequest(for request:
URLRequest) -> URLRequest
• func startLoading()
• func stopLoading()
•
•
•
•
•
https://www.raywenderlich.com/76735/using-nsurlprotocol-swift
URLProtocol
• `true`
•
• `false` URLProtocol
override class func canInit(with request: URLRequest) -> Bool {
return true
}
• 'canonical'
• 'canonical'
•
override class func canonicalRequest(for request: URLRequest) -> URLRequest {
return request
}
override func startLoading() {
// Bundle JSON
guard
let path = Bundle.main.path(forResource: "user", ofType: "json"),
let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else
{
//
}
let client = self.client
let response = HTTPURLResponse(url: request.url!, statusCode: 200,
httpVersion: "HTTP/1.1", headerFields: ["Content-Type" : "application/
json;"])
//
client?.urlProtocol(self, didReceive: response!,
cacheStoragePolicy: .notAllowed)
//
client?.urlProtocol(self, didLoad: data)
//
client?.urlProtocolDidFinishLoading(self)
}
override func startLoading() {
...
//
let client = self.client
let response = HTTPURLResponse(url: request.url!, statusCode: 500,
httpVersion: "HTTP/1.1", headerFields: ["Content-Type" : "application/
json;"])
//
client?.urlProtocol(self, didReceive: response!,
cacheStoragePolicy: .notAllowed)
//
let error = NSError(domain: "CustomURLProtocolError", code: 10001,
userInfo: nil)
client?.urlProtocol(self, didFailWithError: error)
return
....
}
URLProtocolClient
• URLProtocol "URL Loading
System"
• func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy)
• func urlProtocol(URLProtocol, didLoad: Data)
• func urlProtocolDidFinishLoading(URLProtocol)
• func urlProtocol(URLProtocol, didFailWithError: Error)
• func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse)
• func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
URLProtocolClient
• URLProtocol "URL Loading
System"
• func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy)
• func urlProtocol(URLProtocol, didLoad: Data)
• func urlProtocolDidFinishLoading(URLProtocol)
• func urlProtocol(URLProtocol, didFailWithError: Error)
• func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse)
• func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
URLProtocolClient
• URLProtocol "URL Loading
System"
• func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy)
• func urlProtocol(URLProtocol, didLoad: Data)
• func urlProtocolDidFinishLoading(URLProtocol)
• func urlProtocol(URLProtocol, didFailWithError: Error)
• func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge)
• func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse)
• func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
•
• URLSession
GCD
override func stopLoading() {
}
URLProtocol
• `application(_:
didFinishLaunchingWithOptions:)`
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
URLProtocol.registerClass(CustomURLProtocol.self)
return true
}
URL Loading System
•
•
let request = URLRequest(url: URL(string: "https://api.test.com/users/
foo")!)
let task = URLSession.shared.dataTask(with: request) { (data, response,
error) in
//
}
task.resume()
• Flags
#if DEBUG
let path = Bundle.main.path(forResource: "user", ofType: "json")!
let data = try! Data(contentsOf: URL(fileURLWithPath: path))
DispatchQueue.global().async {
//
}
#else
let request = URLRequest(url: URL(string: "https://api.test.com/users/foo")!)
let task = URLSession.shared.dataTask(with: request) { (data, response, error)
in
//
}
task.resume()
#endif
URLSession.shared
•
•
• Flags
let request = URLRequest(url: URL(string: "https://api.test.com/users/
foo")!)
let task = URLSession.shared.dataTask(with: request) { (data, response,
error) in
//
}
task.resume()
• `application(_:
didFinishLaunchingWithOptions:)`
func application(_ application: UIApplication, didFinishLaunchingWithOptions
launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//
URLProtocol.registerClass(CustomURLProtocol.self)
return true
}
URL Loading System
URLSession.shared
• The shared session uses the shared NSURLCache,
NSHTTPCookieStorage, and NSURLCredentialStorage
objects, uses a shared custom networking protocol list
(configured with registerClass(_:) and unregisterClass(_:)),
and is based on a default configuration.
• In other words, if you’re doing anything with caches,
cookies, authentication, or custom networking protocols,
you should probably be using a default session instead of
the shared session.
https://developer.apple.com/documentation/foundation/urlsession/1409000-shared
• URLSession.shared
URLSessionConfiguration
•
URLSessionConfiguration.default URLSession
• URLProtocol.registerClass
URLProtocol.registerClass(CustomURLProtocol.self)
• URLSessionConfiguration
var protocolClasses: [AnyClass]?
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomURLProtocol.self]
let session = URLSession(configuration: config)
let task = session.dataTask(with: urlRequest) { (data, response, error) in
...
}
• URLProtocol URLSessionConfiguration
SessionManager
• ( ) SessionManager
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomURLProtocol.self]
self.manager = SessionManager(configuration: config) //
manager.request(url).response { response in
...
}
Alamofire
• URLProtocol URLSessionConfiguration
URLSessionAdapter Session
let config = URLSessionConfiguration.default
config.protocolClasses = [CustomURLProtocol.self]
let adapter = URLSessionAdapter(configuration: config)
let session = Session(adapter: adapter)
session.send(request) { (result) in
...
}
APIKit
•
• API
• Qiita API
API
URLProtocol
• https://github.com/Alamofire/Alamofire/
blob/master/Tests/URLProtocolTests.swift
• https://github.com/ishkawa/APIKit/blob/
master/Tests/APIKitTests/TestComponents/
HTTPStub.swift
• https://github.com/AliSoftware/
OHHTTPStubs
Appendix
• [URL Loading System]: https://developer.apple.com/library/content/
documentation/Cocoa/Conceptual/URLLoadingSystem/
URLLoadingSystem.html
• [URLProtocol]: https://developer.apple.com/documentation/foundation/
urlprotocol
• [Using NSURLProtocol with Swift]: https://www.raywenderlich.com/76735/
using-nsurlprotocol-swift
• [iOS Advent Calendar 2011 5 / NSURLProtocol ]: http://
faultier.blog.jp/archives/1762587.html
• [Using NSURLProtocol for Testing]: https://yahooeng.tumblr.com/post/
141143817861/using-nsurlprotocol-for-testing

More Related Content

What's hot

Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Filling the flask
Filling the flaskFilling the flask
Filling the flaskJason Myers
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Elena Kolevska
 
Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...Jesus Manuel Olivas
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkMichael Peacock
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Lar21
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101Samantha Geitz
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsMichael Peacock
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystemJames Akwuh
 
SP Rest API Documentation
SP Rest API DocumentationSP Rest API Documentation
SP Rest API DocumentationIT Industry
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgnitermirahman
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 
JWT - Sécurisez vos APIs
JWT - Sécurisez vos APIsJWT - Sécurisez vos APIs
JWT - Sécurisez vos APIsAndré Tapia
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overviewYehuda Katz
 

What's hot (20)

Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
How to use soap component
How to use soap componentHow to use soap component
How to use soap component
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Filling the flask
Filling the flaskFilling the flask
Filling the flask
 
Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5Bootstrat REST APIs with Laravel 5
Bootstrat REST APIs with Laravel 5
 
Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...Creating a modern web application using Symfony API Platform, ReactJS and Red...
Creating a modern web application using Symfony API Platform, ReactJS and Red...
 
Dance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech TalkDance for the puppet master: G6 Tech Talk
Dance for the puppet master: G6 Tech Talk
 
Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18Flask - Backend com Python - Semcomp 18
Flask - Backend com Python - Semcomp 18
 
REST APIs in Laravel 101
REST APIs in Laravel 101REST APIs in Laravel 101
REST APIs in Laravel 101
 
Play!ng with scala
Play!ng with scalaPlay!ng with scala
Play!ng with scala
 
Kyiv.py #17 Flask talk
Kyiv.py #17 Flask talkKyiv.py #17 Flask talk
Kyiv.py #17 Flask talk
 
Phpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friendsPhpne august-2012-symfony-components-friends
Phpne august-2012-symfony-components-friends
 
Apollo ecosystem
Apollo ecosystemApollo ecosystem
Apollo ecosystem
 
Phinx talk
Phinx talkPhinx talk
Phinx talk
 
SP Rest API Documentation
SP Rest API DocumentationSP Rest API Documentation
SP Rest API Documentation
 
ACL in CodeIgniter
ACL in CodeIgniterACL in CodeIgniter
ACL in CodeIgniter
 
WebGUI Developers Workshop
WebGUI Developers WorkshopWebGUI Developers Workshop
WebGUI Developers Workshop
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
JWT - Sécurisez vos APIs
JWT - Sécurisez vos APIsJWT - Sécurisez vos APIs
JWT - Sécurisez vos APIs
 
Rails 3 overview
Rails 3 overviewRails 3 overview
Rails 3 overview
 

Similar to URLProtocol

An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Reaching out from ADF Mobile (ODTUG KScope 2014)
Reaching out from ADF Mobile (ODTUG KScope 2014)Reaching out from ADF Mobile (ODTUG KScope 2014)
Reaching out from ADF Mobile (ODTUG KScope 2014)Luc Bors
 
Express Presentation
Express PresentationExpress Presentation
Express Presentationaaronheckmann
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングscalaconfjp
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Ngoc Dao
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationRouven Weßling
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Joe Keeley
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in SwiftPeter Friese
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Restap ito uploadfilessharepoint
Restap ito uploadfilessharepointRestap ito uploadfilessharepoint
Restap ito uploadfilessharepointMAHESH NEELANNAVAR
 
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationNordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationRouven Weßling
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application FrameworkSimon Willison
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
API Days Australia - Automatic Testing of (RESTful) API Documentation
API Days Australia  - Automatic Testing of (RESTful) API DocumentationAPI Days Australia  - Automatic Testing of (RESTful) API Documentation
API Days Australia - Automatic Testing of (RESTful) API DocumentationRouven Weßling
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by expressShawn Meng
 

Similar to URLProtocol (20)

An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Reaching out from ADF Mobile (ODTUG KScope 2014)
Reaching out from ADF Mobile (ODTUG KScope 2014)Reaching out from ADF Mobile (ODTUG KScope 2014)
Reaching out from ADF Mobile (ODTUG KScope 2014)
 
Express Presentation
Express PresentationExpress Presentation
Express Presentation
 
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディングXitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
Xitrum Web Framework Live Coding Demos / Xitrum Web Framework ライブコーディング
 
Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014Xitrum @ Scala Matsuri Tokyo 2014
Xitrum @ Scala Matsuri Tokyo 2014
 
API Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API DocumentationAPI Days Paris - Automatic Testing of (RESTful) API Documentation
API Days Paris - Automatic Testing of (RESTful) API Documentation
 
Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019Rethinking Syncing at AltConf 2019
Rethinking Syncing at AltConf 2019
 
async/await in Swift
async/await in Swiftasync/await in Swift
async/await in Swift
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Restap ito uploadfilessharepoint
Restap ito uploadfilessharepointRestap ito uploadfilessharepoint
Restap ito uploadfilessharepoint
 
Nordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API DocumentationNordic APIs - Automatic Testing of (RESTful) API Documentation
Nordic APIs - Automatic Testing of (RESTful) API Documentation
 
Laravel 5
Laravel 5Laravel 5
Laravel 5
 
RESTAPI_SPHOSTED_APP
RESTAPI_SPHOSTED_APPRESTAPI_SPHOSTED_APP
RESTAPI_SPHOSTED_APP
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
API Days Australia - Automatic Testing of (RESTful) API Documentation
API Days Australia  - Automatic Testing of (RESTful) API DocumentationAPI Days Australia  - Automatic Testing of (RESTful) API Documentation
API Days Australia - Automatic Testing of (RESTful) API Documentation
 
Jersey
JerseyJersey
Jersey
 
Build web application by express
Build web application by expressBuild web application by express
Build web application by express
 

More from Kosuke Matsuda (11)

Combine
CombineCombine
Combine
 
Swift 5.1 - Property Wrapper
Swift 5.1 - Property WrapperSwift 5.1 - Property Wrapper
Swift 5.1 - Property Wrapper
 
Swift 5.1
Swift 5.1Swift 5.1
Swift 5.1
 
Build Time Analyzer
Build Time AnalyzerBuild Time Analyzer
Build Time Analyzer
 
SafeArea
SafeAreaSafeArea
SafeArea
 
APIKit
APIKitAPIKit
APIKit
 
Core Data
Core DataCore Data
Core Data
 
Impression of Rails 3
Impression of Rails 3Impression of Rails 3
Impression of Rails 3
 
Rails with mongodb
Rails with mongodbRails with mongodb
Rails with mongodb
 
Prototypejs
PrototypejsPrototypejs
Prototypejs
 
GAE_20100112
GAE_20100112GAE_20100112
GAE_20100112
 

Recently uploaded

(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 

Recently uploaded (20)

(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur EscortsCall Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
Call Girls Service Nagpur Tanvi Call 7001035870 Meet With Nagpur Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCRCall Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
Call Us -/9953056974- Call Girls In Vikaspuri-/- Delhi NCR
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 

URLProtocol

  • 4. #if DEBUG DispatchQueue.global().async { // let user = User.mockData() // } #else let request = URLRequest(url: URL(string: "https://api.test.com/ users/foo")!) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // } task.resume() #endif
  • 8. URL Loading System The URL loading system is a set of classes and protocols that allow your app to access content referenced by a URL. At the heart of this technology is the NSURL class, which lets your app manipulate URLs and the resources they refer to. https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ URLLoadingSystem/URLLoadingSystem.html
  • 9. URL loading system • ftp:// • http:// • https:// • file:/// • data:
  • 11.
  • 12.
  • 14. URLProtocol An NSURLProtocol object handles the loading of protocol-specific URL data. The NSURLProtocol class itself is an abstract class that provides the infrastructure for processing URLs with a specific URL scheme. You create subclasses for any custom protocols or URL schemes that your app supports. https://developer.apple.com/documentation/foundation/urlprotocol
  • 16.
  • 18. • class func canInit(with request: URLRequest) - > Bool • class func canonicalRequest(for request: URLRequest) -> URLRequest • func startLoading() • func stopLoading()
  • 19.
  • 22. • `true` • • `false` URLProtocol override class func canInit(with request: URLRequest) -> Bool { return true }
  • 23. • 'canonical' • 'canonical' • override class func canonicalRequest(for request: URLRequest) -> URLRequest { return request }
  • 24. override func startLoading() { // Bundle JSON guard let path = Bundle.main.path(forResource: "user", ofType: "json"), let data = try? Data(contentsOf: URL(fileURLWithPath: path)) else { // } let client = self.client let response = HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: ["Content-Type" : "application/ json;"]) // client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) // client?.urlProtocol(self, didLoad: data) // client?.urlProtocolDidFinishLoading(self) }
  • 25. override func startLoading() { ... // let client = self.client let response = HTTPURLResponse(url: request.url!, statusCode: 500, httpVersion: "HTTP/1.1", headerFields: ["Content-Type" : "application/ json;"]) // client?.urlProtocol(self, didReceive: response!, cacheStoragePolicy: .notAllowed) // let error = NSError(domain: "CustomURLProtocolError", code: 10001, userInfo: nil) client?.urlProtocol(self, didFailWithError: error) return .... }
  • 26. URLProtocolClient • URLProtocol "URL Loading System" • func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy) • func urlProtocol(URLProtocol, didLoad: Data) • func urlProtocolDidFinishLoading(URLProtocol) • func urlProtocol(URLProtocol, didFailWithError: Error) • func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse) • func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
  • 27. URLProtocolClient • URLProtocol "URL Loading System" • func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy) • func urlProtocol(URLProtocol, didLoad: Data) • func urlProtocolDidFinishLoading(URLProtocol) • func urlProtocol(URLProtocol, didFailWithError: Error) • func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse) • func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
  • 28. URLProtocolClient • URLProtocol "URL Loading System" • func urlProtocol(URLProtocol, didReceive: URLResponse, cacheStoragePolicy: URLCache.StoragePolicy) • func urlProtocol(URLProtocol, didLoad: Data) • func urlProtocolDidFinishLoading(URLProtocol) • func urlProtocol(URLProtocol, didFailWithError: Error) • func urlProtocol(URLProtocol, didReceive: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, didCancel: URLAuthenticationChallenge) • func urlProtocol(URLProtocol, wasRedirectedTo: URLRequest, redirectResponse: URLResponse) • func urlProtocol(URLProtocol, cachedResponseIsValid: CachedURLResponse)
  • 31. • `application(_: didFinishLaunchingWithOptions:)` func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // URLProtocol.registerClass(CustomURLProtocol.self) return true } URL Loading System
  • 32. • • let request = URLRequest(url: URL(string: "https://api.test.com/users/ foo")!) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // } task.resume()
  • 33. • Flags #if DEBUG let path = Bundle.main.path(forResource: "user", ofType: "json")! let data = try! Data(contentsOf: URL(fileURLWithPath: path)) DispatchQueue.global().async { // } #else let request = URLRequest(url: URL(string: "https://api.test.com/users/foo")!) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // } task.resume() #endif
  • 35.
  • 36. • • • Flags let request = URLRequest(url: URL(string: "https://api.test.com/users/ foo")!) let task = URLSession.shared.dataTask(with: request) { (data, response, error) in // } task.resume()
  • 37. • `application(_: didFinishLaunchingWithOptions:)` func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // URLProtocol.registerClass(CustomURLProtocol.self) return true } URL Loading System
  • 38. URLSession.shared • The shared session uses the shared NSURLCache, NSHTTPCookieStorage, and NSURLCredentialStorage objects, uses a shared custom networking protocol list (configured with registerClass(_:) and unregisterClass(_:)), and is based on a default configuration. • In other words, if you’re doing anything with caches, cookies, authentication, or custom networking protocols, you should probably be using a default session instead of the shared session. https://developer.apple.com/documentation/foundation/urlsession/1409000-shared
  • 39. • URLSession.shared URLSessionConfiguration • URLSessionConfiguration.default URLSession • URLProtocol.registerClass URLProtocol.registerClass(CustomURLProtocol.self)
  • 40. • URLSessionConfiguration var protocolClasses: [AnyClass]? let config = URLSessionConfiguration.default config.protocolClasses = [CustomURLProtocol.self] let session = URLSession(configuration: config) let task = session.dataTask(with: urlRequest) { (data, response, error) in ... }
  • 41. • URLProtocol URLSessionConfiguration SessionManager • ( ) SessionManager let config = URLSessionConfiguration.default config.protocolClasses = [CustomURLProtocol.self] self.manager = SessionManager(configuration: config) // manager.request(url).response { response in ... } Alamofire
  • 42. • URLProtocol URLSessionConfiguration URLSessionAdapter Session let config = URLSessionConfiguration.default config.protocolClasses = [CustomURLProtocol.self] let adapter = URLSessionAdapter(configuration: config) let session = Session(adapter: adapter) session.send(request) { (result) in ... } APIKit
  • 43.
  • 46. Appendix • [URL Loading System]: https://developer.apple.com/library/content/ documentation/Cocoa/Conceptual/URLLoadingSystem/ URLLoadingSystem.html • [URLProtocol]: https://developer.apple.com/documentation/foundation/ urlprotocol • [Using NSURLProtocol with Swift]: https://www.raywenderlich.com/76735/ using-nsurlprotocol-swift • [iOS Advent Calendar 2011 5 / NSURLProtocol ]: http:// faultier.blog.jp/archives/1762587.html • [Using NSURLProtocol for Testing]: https://yahooeng.tumblr.com/post/ 141143817861/using-nsurlprotocol-for-testing