SlideShare a Scribd company logo
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

Natalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in KrakówNatalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in Krakówbim.edu.pl
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf884710SadaqatAli
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdfKamal Acharya
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxR&R Consult
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdfKamal Acharya
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdfAhmedHussein950959
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringC Sai Kiran
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsAtif Razi
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfAyahmorsy
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGKOUSTAV SARKAR
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdfKamal Acharya
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfKamal Acharya
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectRased Khan
 
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...Amil baba
 
Fruit shop management system project report.pdf
Fruit shop management system project report.pdfFruit shop management system project report.pdf
Fruit shop management system project report.pdfKamal Acharya
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxVishalDeshpande27
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdfKamal Acharya
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdfRESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdfKamal Acharya
 
Electrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineElectrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineJulioCesarSalazarHer1
 

Recently uploaded (20)

Natalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in KrakówNatalia Rutkowska - BIM School Course in Kraków
Natalia Rutkowska - BIM School Course in Kraków
 
Explosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdfExplosives Industry manufacturing process.pdf
Explosives Industry manufacturing process.pdf
 
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdfONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
ONLINE VEHICLE RENTAL SYSTEM PROJECT REPORT.pdf
 
Laundry management system project report.pdf
Laundry management system project report.pdfLaundry management system project report.pdf
Laundry management system project report.pdf
 
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptxCFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
CFD Simulation of By-pass Flow in a HRSG module by R&R Consult.pptx
 
Online blood donation management system project.pdf
Online blood donation management system project.pdfOnline blood donation management system project.pdf
Online blood donation management system project.pdf
 
ASME IX(9) 2007 Full Version .pdf
ASME IX(9)  2007 Full Version       .pdfASME IX(9)  2007 Full Version       .pdf
ASME IX(9) 2007 Full Version .pdf
 
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical EngineeringIntroduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
Introduction to Machine Learning Unit-4 Notes for II-II Mechanical Engineering
 
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical SolutionsRS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
RS Khurmi Machine Design Clutch and Brake Exercise Numerical Solutions
 
Peek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdfPeek implant persentation - Copy (1).pdf
Peek implant persentation - Copy (1).pdf
 
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWINGBRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
BRAKING SYSTEM IN INDIAN RAILWAY AutoCAD DRAWING
 
Online resume builder management system project report.pdf
Online resume builder management system project report.pdfOnline resume builder management system project report.pdf
Online resume builder management system project report.pdf
 
A case study of cinema management system project report..pdf
A case study of cinema management system project report..pdfA case study of cinema management system project report..pdf
A case study of cinema management system project report..pdf
 
Arduino based vehicle speed tracker project
Arduino based vehicle speed tracker projectArduino based vehicle speed tracker project
Arduino based vehicle speed tracker project
 
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
NO1 Pandit Black Magic Removal in Uk kala jadu Specialist kala jadu for Love ...
 
Fruit shop management system project report.pdf
Fruit shop management system project report.pdfFruit shop management system project report.pdf
Fruit shop management system project report.pdf
 
shape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptxshape functions of 1D and 2 D rectangular elements.pptx
shape functions of 1D and 2 D rectangular elements.pptx
 
Event Management System Vb Net Project Report.pdf
Event Management System Vb Net  Project Report.pdfEvent Management System Vb Net  Project Report.pdf
Event Management System Vb Net Project Report.pdf
 
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdfRESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
RESORT MANAGEMENT AND RESERVATION SYSTEM PROJECT REPORT.pdf
 
Electrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission lineElectrostatic field in a coaxial transmission line
Electrostatic field in a coaxial transmission line
 

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