lecture 6 Closures, Networking, CocoaPods

Similar documents
lecture 1 hello, swift cs : spring 2018

Backends and Databases. Dr. Sarah Abraham

Developing Applications for ios

lecture 11 Advanced Swift

Building a testable mixed-codebase ios Framework

Backends and Databases. Dr. Sarah Abraham

Stream iphone Sensor Data to Adafruit IO

Mobile Development - Lab 2

Announcements. Lab 3 is due on Wednesday by 11:59 PM

ios DeCal : Lecture 2 Structure of ios Applications: MVC and Auto Layout

CS50 Quiz Review. November 13, 2017

CS193p Spring 2010 Thursday, April 29, 2010

What s New in Foundation for Swift Session 207

Swift. Mobile Application Development in ios School of EECS Washington State University Instructor: Larry Holder

What s New in Cocoa. App Frameworks #WWDC17. Ali Ozer Daphne Larose

Brain Corporate Bulk SMS

CS61C Machine Structures. Lecture 3 Introduction to the C Programming Language. 1/23/2006 John Wawrzynek. www-inst.eecs.berkeley.

CS193P - Lecture 3. iphone Application Development. Custom Classes Object Lifecycle Autorelease Properties

Composer Help. Web Request Common Block

LEARNING ios APP DEVELOPMENT With Swift 3 & ios 10

Welcome to CS50 section! This is Week 10 :(

Seamless Linking to Your App

Book keeping. Will post HW5 tonight. OK to work in pairs. Midterm review next Wednesday

Kick Off Meeting. OMi Management Pack Development Workshop. 23rd May 2016

Session 9. Deployment Descriptor Http. Reading and Reference. en.wikipedia.org/wiki/http. en.wikipedia.org/wiki/list_of_http_headers

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Distributed Systems. 03. Remote Procedure Calls. Paul Krzyzanowski. Rutgers University. Fall 2017

Creating Audio Apps for watchos

CSE P 501 Compilers. Parsing & Context-Free Grammars Hal Perkins Spring UW CSE P 501 Spring 2018 C-1

COMP 524 Spring 2018 Midterm Thursday, March 1

Swift 5, ABI Stability and

Learning vrealize Orchestrator in action V M U G L A B

Writing your first Web Data Connector

Getting the Most Out of HealthKit

Content Protection for HTTP Live Streaming

Announcement. Final Project Proposal Presentations and Updates

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

FAQs. A guide for school app administrators

CS109 Data Science Data Munging

CSCI-1200 Data Structures Spring 2018 Lecture 14 Associative Containers (Maps), Part 1 (and Problem Solving Too)

Nick Terkay CSCI 7818 Web Services 11/16/2006

CS193p Spring 2010 Wednesday, March 31, 2010

CS 417 9/18/17. Paul Krzyzanowski 1. Socket-based communication. Distributed Systems 03. Remote Procedure Calls. Sample SMTP Interaction

Miscellaneous Topics

REST. Web-based APIs

Administrivia. IBM Info Session Date: Wed,, Jan 13 Time: 5:30 7 pm Location: Wesbrook 100

Introducing the Modern WebKit API

Which of the following expressions has the type int list?

CS193X: Web Programming Fundamentals

EDA Spring, Project Guidelines

COMP327 Mobile Computing Session:

Programming Languages and Techniques (CIS120)

Lab 01 How to Survive & Introduction to Git. Web Programming DataLab, CS, NTHU

Youth Stat & VEOCI Tutorials

Final Exam. Programming Assignment 3. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu. Readings

Swift. Introducing swift. Thomas Woodfin

APIs and API Design with Python

Enhancing your apps for the next dimension of touch

What we already know. Late Days. CSE 444: Database Internals. Lecture 3 DBMS Architecture

Department of Computer Science. COS 122 Operating Systems. Practical 3. Due: 22:00 PM

SWIFT - CLOSURES. Global Functions Nested Functions Closure Expressions. Have a name. Capture values from enclosing function

Using and Extending the Xcode Source Editor

XML Processing & Web Services. Husni Husni.trunojoyo.ac.id

Data Delivery with Drag and Drop

Reverse Engineering Swift Apps. Michael Gianarakis Rootcon X 2016

Duration 5 days (For basic crowd 5+3days needed)

CSE 444: Database Internals. Lecture 3 DBMS Architecture

iphone Application Programming Lecture 3: Swift Part 2

CSE 332: Data Structures and Parallelism Winter 2019 Setting Up Your CSE 332 Environment

Student Guide. Document Version: This guide documents features available in NETLAB+ VE version and later.

SWIFT & #IOExtendedCLT, 18th May 2016

ITP 342 Mobile App Dev

Project Compiler. CS031 TA Help Session November 28, 2011

Announcements. JSon Data Structures. JSon Syntax. JSon Semantics: a Tree! JSon Primitive Datatypes. Introduction to Database Systems CSE 414

AdFalcon ios SDK Developer's Guide. AdFalcon Mobile Ad Network Product of Noqoush Mobile Media Group

Realm Mobile Database. Knoxville CocoaHeads April 2017 by Gavin Wiggins

Announcements. Today s Topics

Review! * follows a pointer to its value! & gets the address of a variable! Pearce, Summer 2010 UCB! ! int x = 1000; Pearce, Summer 2010 UCB!

today what is this course about? what is this course about? Welcome to CSC309! Programming on the Web APRIL 05

Create-A-Page Design Documentation

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Profile Can't Be Found Jenkins

CS61C : Machine Structures

Optimizing Swift Performance Session 409

Service SDK Developer s Guide for ios PREVIEW

Unit 5: Computer Networking CS 101, Fall 2018

CS 43: Computer Networks. HTTP September 10, 2018

CS 161 Computer Security

CS103 Handout 13 Fall 2012 May 4, 2012 Problem Set 5

CSC 443: Web Programming

Extending Your Apps with SiriKit

ITP 342 Mobile App Dev. Functions

CS193E Lecture #3 Categories and Protocols Cocoa Memory Management

Notes slides from before lecture. CSE 21, Winter 2017, Section A00. Lecture 10 Notes. Class URL:

Notes slides from before lecture. CSE 21, Winter 2017, Section A00. Lecture 4 Notes. Class URL:

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Welcome to CS 241 Systems Programming at Illinois

Campus Automation. Joe Neville Aruba Consulting System Engineer

Software Engineering Large Practical

Introducing MusicKit. Media #WWDC17. Tim Parthemore, MusicKit Services Joel Lopes Da Silva, ios Music

Transcription:

lecture 6 Closures, Networking, CocoaPods cs198-001 : spring 2018

announcements no new lab this week - continuation of Pokedex lab + custom app workday (attendance still required) Pokedex due Wednesday at 11:59 pm submit on Gradescope ONLY if you do not finish during lab hw3 pt 1 (snapchat clone) due tonight custom app specification released tonight Due next Monday 3/19 at 11:59pm

final presentations sometime during dead week staff selected top app submissions will be asked to present (prizes!) spec released tonight!!

today s lecture Closures Networking CocoaPods Alamofire

closures Closures are self-contained blocks of functionality that can be passed around and used in your code.

closures Closures are self-contained blocks of functionality that can be passed around and used in your code. They can capture and store references to any constants and variables from the context in which they are defined Global closure functions: Named, do not capture values Nested closure functions: Named, capture values from enclosing function

format of a closure { (parameters) -> return type in } statements

functions vs closures func isgood(string: String) -> Bool { return string == "OK" } isgood(string == "OK")

functions vs closures func isgood(string: String) -> Bool { return string == "OK" } isgood(string == "OK") let isgoodclosure = {(string: String) -> Bool in return string == "OK" } isgoodclosure("ok") In Swift, functions are just a special case of closures!

global closures let intpow = {(val1: Int, val2: Int) -> Int in return Int(pow(Double(val1), Double(val2))) } let result = intpow(2, 10) print(result)

shorthand closures let closure1 = { (i: Int) -> Int in return i * 2 } // Closures can be type-inferenced, just like functions let closure2 = { i in return i * 2 } // If we only have one line, we can omit return let closure3 = { i in i * 2 } // We can also specify variables using $[position] syntax rather than explicitly defining them let closure4 = { $0 * 2 }

nested closures func makeincrementer(forincrement amount: Int) -> () -> Int { var runningtotal = 0 func incrementer() -> Int { runningtotal += amount return runningtotal } return incrementer } var incrementer = makeincrementer(forincrement: 5)

nested closures func makeincrementer(forincrement amount: Int) -> () -> Int { var runningtotal = 0 func incrementer() -> Int { runningtotal += amount return runningtotal } return incrementer } var incrementer = makeincrementer(forincrement: 5) Used frequently in network calls!

why closures? Completion Blocks func longaction(completion: () -> ()) { for index in superbigarray { // do some really time consuming stuff } // notify the caller that longaction is finished completion() } Higher Order Functions let array = [1, 2, 3] let arraytimestwo = array.map{ i in return i * 2 }

networking

networking and ios Networking is acquiring/passing data to/from some URL that exists on the world wide web or a local server General structure as it relates to ios Recipient Address Parameters Response

what is an api? application programming interface abstraction layer between two software components used throughout computer science (OS s, hardware, my cool ios app! databases)

what is an api? application programming interface api abstraction layer between two software server components used throughout computer science (OS s, hardware, my cool ios app! databases) client (you!)

what is an api? example: you want to create an map related app! one option: create a map application and gather data from scratch another option: integrate google maps data into your app, my cool ios app! using an api!

what is an api? another example: you ve gathered extensive data and have created a database/app using it share this data with other developers through your own api my cool ios app!

why are apis used? save time hide implementation details while providing functionality modularity my cool ios app!

how to use APIs in ios applications RESTful API calls (via a URL) ios SDKs (quite a few are still in Obj-C but there are often Swift versions!)

RESTful APIs

RESTful apis representational state transfer uses HTTP requests to GET, PUT, POST and DELETE data. Parameters Response requests will return responses (XML, YAML, JSON)

RESTful apis + HTTP methods http://maps.google.com/maps/api/geocode/json? address=berkeley server

RESTful apis + HTTP methods http://maps.google.com/maps/api/geocode/json? address=berkeley resources

RESTful apis + HTTP methods http://maps.google.com/maps/api/geocode/json? address=berkeley parameters

response

JSON Javascript Object Notation easy to send to / from server language independent readable! { "id": "883836255014203", "likes": { "data": [ { "name": Soda Hall", "id": "213133108715544", "created_time": "2017-08-22:" }, { "name": ios decal", "id": "104681762916482", "created_time": "2017-08-21" }, { "name": Oski", "id": "548276038608761", "created_time": 2017-07-17"...

but how do we do this in ios? making requests - URLRequest, URLSession (built in), or Alamofire (3rd party) parsing - JSONSerialization (built in) or SwiftyJSON (3rd party)

URLSession

URLSession Apple s API for downloading content Support various URL schemes HTTP, HTTPS, FTP, Data, File Pass in a URL URL object, allocated from String

Some Relevant Classes URL Object that contains URL URLRequest Contains URL, request method, etc. URLResponse Contains info for server s response

URLSession Workflow 1) Create URL from a String 2) Create URLSession 3) Create a URLSessionDataTask Get data from the task and save it

URLSessionDataTask datataskwithurl - Default HTTP GET datataskwithrequest - Can specify HTTP in the form of a NSURLRequest

URLSession func loadimage() { let url = URL(string: https://iosdecal.com/img.jpg") let session = URLSession.shared let task = session.datatask(with: url!, completionhandler: { (data, response, error) -> Void in if error == nil { let img = UIImage.init(data: data!) self.imageview.image = img } }) } task.resume()

JSON parsing in ios JSONSerialization using jsonobject jsonobject(with: options:)

JSON parsing in ios JSONSerialization using jsonobject jsonobject(with: options:) let data: Data = [received from network request] let json = try? JSONSerialization.jsonObject(with: data, options: []) // Do stuff with your JSON if let names = json["names"] as? [String] { } print(names)

accessing values from json // Example JSON with object root: /* { "somekey": 42.0, "anotherkey": { "somenestedkey": true } } */ if let dictionary = json as? [String: Any] { if let number = dictionary["somekey"] as? Double { // access individual value in dictionary } } example link

parsing via initializers struct Dog { init?(json: [String: Any]) { guard let name = json["name"] as? String, let friends = json["friends"] as? [String], let bestfriendname = friends[0], let secondbestfriendname = friends[1], let meals = json[ meals"] as? [String: Any], else { return nil } We can create model objects from JSON!

CocoaPods

What are CocoaPods A dependency manager for Cocoa Projects CocoaPods are Swift and Objective-C classes that other people write for you that you can use in your project: Makes life more efficient and easier

What are CocoaPods A dependency manager for Cocoa Projects

Timepiece Adding A Year To the Current Date: Without Timepiece: let calendar = NSCalendar.currentCalendar() let newdate = calendar.datebyaddingunit(.year, value: 1, todate: NSDate(), options: NSCalendarOptions.MatchNextTime) With Timepiece let newdate = now + 1.year

How to use CocoaPods

Install CocoaPods sudo gem install cocoapods Or if you prefer Homebrew: brew install cocoapods

Make a Podfile 1. Just named Podfile with no extension 2. Format Hint: pod init does this automatically!

Update Dependencies Once you have your podfile, pod install

Open.xcworkspace

Check In!

Alamofire

Alamofire : Networking in Swift HTTP networking library written in Swift Simplifies common networking tasks Request/Response methods JSON serialization Authentication GitHub link

Alamofire : Requests.request: HTTP requests.upload: Upload large files.download: Download large files or resume a download already in progress.

Alamofire : Request types Alamofire.request("https://httpbin.org/get") // default is GET Alamofire.request("https://httpbin.org/post", method:.post)

Alamofire : Response Handlers // Response Data Handler - Serialized into Data func responsedata(queue: DispatchQueue?, completionhandler: @escaping (DataResponse<Data>) -> Void) -> Self // Response JSON Handler - Serialized into Any func responsejson(queue: DispatchQueue?, completionhandler: @escaping (DataResponse<Any>) -> Void) -> Self

Alamofire : Response Validation Alamofire.request("https://httpbin.org/get ).validate().responsejson { response in switch response.result { case.success: print("validation Successful") case.failure(let error): print(error) } }

Alamofire : Parameters Alamofire.request("https://httpbin.org/post", method:.post, parameters: parameters) Alamofire.request("https://httpbin.org/post", method:.post, parameters: parameters, encoding: URLEncoding.default)

Alamofire : Authentication let user = "user" let password = "password" Alamofire.request( https:// httpbin.org/basic-auth/\(user)/\ (password)").authenticate(user: user, password: password).responsejson { response in debugprint(response) }