IOS 8 Programming - With Swift a Step by Step Guide Book for Beginners

download IOS 8 Programming - With Swift a Step by Step Guide Book for Beginners

of 118

description

IOS 8 Programming - With Swift A Step By Step Guide Book For Beginners

Transcript of IOS 8 Programming - With Swift a Step by Step Guide Book for Beginners

  • iOS8ProgrammingwithSwift

    AStepByStepGuideBookforBeginners.CreateYourOwnAppinOneDay!

    KevinLyn.

    Copyright2015byKevinLyn.

    All rights reserved. No part of this publication may be reproduced, distributed, or

    transmitted in any form or by any means, including photocopying, recording, or other

    electronic or mechanical methods, without the prior written permission of the author,

    except in the case of brief quotations embodied in critical reviews and certain other

    noncommercialusespermittedbycopyrightlaw.

    Disclaimer

    While all attemptshavebeenmade toverify the informationprovided in this book, theauthordoesntassumeanyresponsibilityforerrors,omissions,orcontraryinterpretationsof the subjectmatter containedwithin.The information provided in this book is foreducationalandentertainmentpurposesonly.Thereaderisresponsibleforhisorherownactionsandtheauthordoesnotacceptanyresponsibilitiesforanyliabilitiesordamages,realorperceived,resultingfromtheuseofthisinformation.

  • Contents

    BookDescription

    Introduction

    Chapter1:Definition

    Chapter2:GettingStartedwithiOS8SwiftProgramming

    Chapter3:VariablesandConstantsinSwift

    Chapter4:TypeAnnotations

    Chapter5:TuplesinSwift

    Chapter6:EnumerationsinSwift

    RawValues

    Chapter7:UIAlertViewinSwift

    Chapter8:NSTimerinSwift

    ProjectSetup

    CodingtheTimer

    StoppingtheNSTimer

    ClearingtheNSTimer

    Chapter9:SwiftandPHP

    PostingfromSwifttoPHP

    HowtoGettheStatusoftheHTTPCode

    Chapter10:ConnectingtoiTunesSearchAPI

    HowtoConnecttheUserInterface

    HowtoMaketheAPIRequest

    HowtoPreparefortheResponse

    HowtoUpdatetheTableViewUI

    Chapter11:ImageLoadingandCachingAsynchronously

  • Chapter12:UsingObjective-CclassesinSwift

    Chapter13:AnimationsinSwift

    ContainerViewTransitions

    Chapter14:CreatinganAudioPlayerwithSwift

    CreatingtheUserInterface

    ActionMethods

    CreationandInitializationofAVAudioPlayerObject

    ImplementationoftheAVAudioPlayerDelegateProtocolMethods

    Conclusion

  • BookDescription

    ThisbookbeginsbyexplainingtheiOS8andtheSwiftprogramminglanguage,including

    theiroriginandfunctionality.ExplanationonhowtogetstartedwithSwiftisavailable,

    includingsettinguptheenvironment.

    Variables,constants,andTupleswhichareusedtostorevaluesinSwifthavebeen

    explored.Onreadingthisbook,youwillgettounderstandhowtocreateanNSTimerfor

    youriOSapp.EnumerationsandTypeannotationsinSwifthavealsobeenexploredin

    detail.YouwillgettounderstandhowtosendsomepostrequesttoaPHPscript,usinga

    server.YouwillalsoknowhowtoloadimagesintoyourSwiftappasynchronously.

    ConnectingyourapptotheiTunesSearchAPIisalsoexamined.Theprocessofimporting

    Objective-CclassesintoSwifthasbeenexplained.AnimationsandplayingaudioinSwift

    havealsobeendiscussed.Programsillustratinghowtoachievetheabovefeatureshave

    beenincluded,aswellaspicturesillustratingthesame.

    Thelanguageusedinthisbookisverysimple,sothatitsuitsboththeexpertsandthe

    beginners.Thefollowingtopicshavebeendiscussed:

    Definition

    GettingStartedwithSwift

    VariablesandConstants.

    TypeAnnotations

  • Tuples

    Enumerations

    UIAlertView

    NSTimerinSwift

    SwiftandPHP

    ConnectingtoiTunesSearchAPI

    ImageLoadingandCachingAsynchronously

    UsingObjective-CClasses

    Animations

    CreatinganAudioPlayer

  • Introduction

    iOS8hasshownimprovedsupportforamazingfeatureswhichwerenotsupportediniOS

    7.ThisexplainstheneedforthecreationofiOS8apps,andthereforetheneedtolearn

    Swift.

    Recently,AppleIncreleasediOS8intothemarket.ThisfollowedareleaseoftheSwift

    programminglanguageforthepurposeofcreatingappstorunondevicessupportingthis

    versionofiOS.Thislanguagehasshownanumberofimprovementsintermsof

    functionalitycomparedtotheObjective-Cprogramminglanguage.

  • Chapter1:

    Definition

    iOSisanoperatingsystemusedonAppledevices.ItwasdevelopedbyAppleInc.inthe

    year2007torunontheiPhone.Itwaslateradvancedtorunonotherdevicessuchasthe

    iPadMini,iPodTouch,AppleTV,andiPad.TheinterfaceofiOSismadeofcontrolssuch

    asbuttons,sliders,andswitches.

    Theuserinterfacereliesondirectmanipulation.UsersinteractwiththeOSthrough

    tapping,swiping,pinching,andreversepinching.iOS8wasdevelopedasasuccessorto

    iOS7,anditistheeighthversionoftheoperatingsystem.Itwasreleasedintheyear

    2014.

    ItmadeseveralimprovementsonwhatwasprovidedbyiOS7intermsoffunctionality

    anduserinterface.SomeofthechangesbroughtaboutbyiOS8includedanadvanced

    photosapp,notificationcenter,HealthKit,andHomeKit.Forinstance,withtheiOS8

    photoapp,usershavemoreeditingcapabilitiesfortheirphotosastheycansetthe

    brightnessandcolortotheirchoice.Thephotoscanalsoberotatedineitheraclockwiseor

    anti-clockwisedirection.ThesefeatureswerenotavailableiniOS7.

    TheNotificationCenteriniOS8hasonlytwotabs,thatis,theTodayand

  • Notificationstabs.IniOS7,thishadthreetabs.Userscannoweditthecomponentsof

    thenotificationcenterbytheadditionofwidgets,andreplyingtomessagesfromthe

    NotificationCenterisnowpossible.

    Themessagingapphasalsobeenimproved,sinceuserscannowsendmessagesincluding

    videosandaudios,aswellassetthemessagestobedeletedafteraperiodofchoice.This

    showsthatiOS8hasbroughtwithitanumberofadvancementsiniOS.Devicesrunning

    iOS8havehitthemarket.iOS8appshavealsoshownalargenumberofdownloads,and

    thisindicatesapositivegrowthinthefuture.

  • Chapter2:

    GettingStartedwithiOS8Swiftprogramming

    SwiftisthenewprogramminglanguageintroducedbyAppletoslowlyreplaceObjective-

    C.ItoffersadvancedfeatureswhicharenotavailableintheObjective-Cprogramming

    language.InSwift,programmerscancombineObjective-C++,Objective-C,andSwiftin

    justasingleprogramsoastotakeadvantageofthefeaturesfromthethreelanguages,

    meaningthatonecancreatecoolandamazingappswiththislanguage.

    HelloWorldApp

    BeforecreatingourHelloWorldapp,downloadthebetaversionofXcode6.Youcanget

    thisfromtheiOSdevelopercenter.Onceyougetthrough,createanewprojectbyclicking

    on:

    File->New->NewProject.Awidowwillappearwithsomeoptionsforyoutochoose.

    SelectSingleviewApplication.

  • Givetheprojectanameofchoice.SelectthelanguagefollowedbychoosingSwift.

    Chooseadirectorytostoreyourproject.Itwillbeoverandreadytogo.Notethatinthere

    Swiftprogramminglanguage,therearenoheadersandwhateveriscodedgoestothe

    .Swiftfile.

    Twotemplatefilesarealsocreated,thatis,ViewController.swiftandAppController.swift.

    Ifyouruntheappatthistime,yougetanemptyview,sowaituntilwedevelopsomeUI

    controls.NoticethatafteryouopentheStoryboard,theviewcontrollerwillhavea

    differentsize,neitherthatoftheiPadnortheiPhone.

    Startbydraggingalabel,followedbytextfield,andfinallyabutton.Alignthemtomake

    surethattheyareinthepositionthatyouwant.

  • Itisnowtimetocreatetheoutlets.JuststartbyselectingtheLabel,holddowntheCtrl

    key,andthendragittothefileontherightwindow.Thiswillformthe

    ViewController.swiftfile.Repeatthisforthreecontrolssothatyoucanhavethreeoutlets.

  • Thethreeoutletswillbeasfollows:

    @IBOutletvarhelloLabel:UILabel

    @IBOutletvarnameTextField:UITextField

    @IBOutletvarhelloButton:UIButton

    IfyouaregoodatprogrammingwithObjective-C,youwillnoticesomesimilaritieswith

    Swift,suchtheIBOutletkeyword.However,thereisanewkeywordoverride.This

    keywordwillbeusedincaseyouoverrideamethodinthesuperclass.Swifthasbrought

    aboutthepreventionofcommonmistakesthatprogrammersmakesincewiththis

    keyword,overridingmethodswithoutrealizingitwillnotbepossible.

    Wethenneedtodeclareamethodtohelpinsettinguptheuserinterface.Thismethodwill

    beasfollows:

    funccreateUI(){

    }

    NoticethesyntaxofdeclaringamethodinSwift.Themethodhasnoargumentsandit

    returnsnothing.OuraimistodisplayaredtextatthecenterofthelabelwrittenHello

    World.Thecodebelowwillachievethis:

    helloLabel.text=HelloSwift!

  • helloLabel.textColor=UIColor.redColor()

    helloLabel.textAlignment=NSTextAlignment.Center

    Noticethatwehavenotusedsemicolonsattheendofthelines,northesymbol@before

    stringliterals.Methodsforspecifyingcolorhavealsobeenspecifiedratherthansending

    somemessagetoUIcolor.Forthepurposeofguidingtheuser,letusaddaplaceholderto

    thetextfield:

    nameTextField.placeholder=Enteryourname

    Tochangethetextdisplayedonthebutton:

    helloButton.setTitle(sayHello,forState:.Normal)

    Nowwearedonewithcreatingtheuserinterface.Itstimetocallthemethodthatwe

    createdearlieron.Thiscanbedoneasfollows:

    overridefuncviewDidLoad(){

    super.viewDidLoad()

    //anyadditionalsetupcanbedonehereafterloadingtheview

    createUI()

    }

  • Wecannowrunourapp.However,letusaddsomefunctionalitytothebutton.Todothis,

    justbringuptheassistanteditorwhileinInterfaceBuilder.Dragtotheviewcontroller

    fromtheUIButtonbypressingtheCtrlkey.NamethemethodashelloAction.Thisshould

    bedoneaftermovingtoactionfromoutlet.

    Wewanttomakethelabeldisplaythetextenteredinthetextfield.Ifnothingwasentered

    inthetextfield,analertdialogshouldbeshownpromptingtheusertoentersometext.

    Thiscanbeachievedusingthecodebelow:

    @IBActionfunchelloAction(sender:AnyObject){

    letnm=nameTextField.text

    ifnm.isEmpty{

    letalertdialog=UIAlertController(title:Error,message:Enteryourname,

    preferredStyle:UIAlertControllerStyle.Alert)

    alertdialog.addAction(UIAlertAction(title:OK,style:UIAlertActionStyle.Default,

  • handler:nil))

    self.presentViewController(alertdialog,animated:true,completion:nil)

    }else{

    helloLabel.text=Hello\(nm)!

    }

    }

    First,wegotthetextfromthetextviewandstoreditinaconstantvariable.Constant

    variablesarehighlyusefulinSwift.Wethencheckwhethertheconstantisemptyor

    containssometext.Ifitisempty,weprovideanalertboxpromptingtheusertoenterhis

    name.

    Ifithassometext,thisnameiscombinedwiththewordHello,sotheoutputwillbe

    Helloname,wherethenameisthetextthatyouenteredinthetextfield.Thishasreally

    shedsomelighttoyouasfarasSwiftisconcerned.

    Ifyouhavealittleprogrammingexperience,thelanguagewillbeeasyforyou.Notice

    thatwehaveusedUIAlertControllerinsteadoftheUIAlertView.ThisisbecauseiniOS8,

    thelattercaneasilycrashourapp,sowearetryingtoavoidthis.

    YoucannowruntheapponaniPhonesimulator.UseiPhone5s.Thefollowingwillbethe

    output:

  • Whenyouenteryournameonthetextfieldandpresstheenterkey,youwillobservea

    changeintheredtext,sincetheSwiftwillchangetothenamethatyouhaveentered.

    Thatisyourfirstapp,whichisveryamazing.

  • Chapter3:

    VariablesandConstantsinSwift

    YoumightneedtostoredataforyouriOS8app.Variablescanbeusedforthispurpose.In

    Swift,valuescanbestoredeitherasavariableorasaconstant.Example:

    varnumber=20

    letresult=15

    Thefirstexampleillustrateshowtostoreavalueasavariable,whereasthesecond

    exampleillustrateshowtostoreavalueasaconstant.Notethekeywordswehaveusedto

    defineaconstantandavariable.

    Youhaverealizedthatwehavenotspecifiedthetypeforourvariableandconstantinthe

    aboveexamples.ThereasonisbecauseSwifthasvalueswhichareimplicitlytypestored.

    However,youcanalsochoosetospecifythetypeofthevalue.Thisismostlydonewhen

    thereisnoinitialization.Swiftwillinferthatsince20isaninteger,theprogrammer

    wantedtostoreaninteger,sotheresultmustalsobeaninteger.Totypeyourvalues,do

    thefollowing:

  • varnumber:Double

    Letconstantsmustalwaysbeinitialized.Thisshouldbethecaseevenifyouhave

    explicitlytypedthem.Youmightwantadoubleaftertypinganintegervalueasshown

    below:

    letvalue:Double=30

    Insteadofstoringthevalue30,itwillstore30.0.

    Thevalueofaconstantcannotbechanged.Tryingtodosowillresultintoanerror:

    letresult=15

    result=22

    Ifyouruntheprogramwiththeabove,thefollowingerrorwillbeseen:

    Error:Cannotassigntoletvalueresult

    Thismessagemeansthatthevaluecannotbechangedasitisaconstant,sodonttrythis

    inSwift.

  • Chapter4:

    TypeAnnotations

    Sometimes,youarenotsurewhetherthespecifiedvalueandtheexpectedvaluematch.

    ThisexplainstheneedfortypeannotationinSwift.Thiscanbeappliedwhenweare

    declaringvariablesandfunctions.TheideabehindtypeannotationsinSwiftisveryeasy,

    asyoujustspecifythekindofvariablethatshouldgointoyourconstantsandvariables.

    SinceSwiftissafewhenitcomestotypes,youmustthenadheretothisbymakingsure

    thatthetypethatyouassignavariableisthesameastheannotatedvariable.However,do

    notbemuchintothisasSwiftcandothisforyou.

    Example:

    AssumingthatyouhaveavariablecalledstudentNameandyouraimistopassastring

    intothisvariable,youcandothisasfollows:

    varstudentName=John

    SwiftwillautomaticallyknowfromthisthatthevariablestudentNameisastring.Letus

    trytopassanintegertothesamevariable:

  • varstudentName=123

    Oncewedothis,thefollowingerrormessagewillbeproduced:

    TypeStringdoesnotconformtoprotocolIntegerLiteralConvertable.

    ThismeansthatSwiftwillpassanintegervaluetoavariableexpectedtobeastring.So,

    incaseyougetsuchanerror,justknowthatyouhaveaproblemwithtypeannotation.

    Youmightneedtospecifyandcreateastringtypeannotationatthebeginningofyour

    program.Thiscanalsobedoneinanotherfilewhichistobeincludedasfollows:

    varstudentName:String;

    IfyouassignastringtothevariablestudentNamelateroninthecodeasshownbelow,all

    willbewell:

    studentName=John

    However,tryingtoassignanintegertothisvariableasshownbelowwillresultintoan

    errormessage:

  • studentName=123

    ThisshowshowtypeannotationsareveryusefulinSwift,andalsoveryeasyto

    understandanduseincoding.

  • Chapter5:

    TuplesinSwift

    TheseareoneofthefeaturesofSwiftprogramminglanguage.Withthem,onecanstore

    multiplevaluesinasinglevalue.Obviously,thesevaluesarecloselyrelatedtoeachother.

    Example:

    varstudent=(John,123,true)

    AboveisanexampleofaTupleinSwift.WheneverSwiftmeets(),itknowsthatithas

    metaTuple.ThevaluesinaTupleareseparatedusingacomma(,).Justlikewhathappens

    inanarray,Tuplessupporttheuseofindices,wherebythefirstelementisatindex0.To

    returntheelementsoftheaboveTuple,wecandothefollowing:

    student.0//=John

    student.1//=123

    student.3//=true

    Otherthantheabovemethod,wecanassignnamestotheelementsofaTuple.Thisis

  • shownbelow:

    varstudent=(name:John,admission:123,isClubMember:true)

    Afterdeclaring,youcangetthevaluesasfollows:

    student.name//etc

    IfyouwanttogetaTuplefromareturnsuchasafunction,youhavetodecomposethe

    partsoftheTupleintovariablesasfollows:

    var(name,admission,isClubMember)=student

    Thevariablescanthenbetypeputasshownbelow:

    1Name

    2Admission

    3isClubMember

    Incaseyoudontwanttoassignavalue,justputanunderscoreinthefieldasshown

    below:

  • var(_,name,_)

    NowyouknowhowtouseTuplesinSwift.MakeuseofthemwhendevelopingiOS8

    apps.Theyarequiteeasytolearnandunderstand,yetveryusefulinSwift.

  • Chapter6:

    EnumerationsinSwift

    Ifyouwanttodefineacommontypeforagroupofitemsorvalueswhicharerelated,then

    enumerationwillhelpyoutodoso.Itsupportssomeofthefeatureswhichwere

    traditionallysupportedbyclassesonly.Thesefeaturesincludeinstancemethodsand

    computedproperties.Initialvaluesofmemberscanalsobedefinedbytheuseof

    enumerations.

    TheyhaveawiderangeofusesinSwiftprogramming,andthisexplainswhyyouneedto

    understandhowtousethem.Mostprogrammersviewenumerationsascomplex,butin

    realsense,theyarenot.

    CreateanewSwiftplayground.InSwift,theyareusuallyreferredtoasenum,sodontget

    confusedwhenyoufindthis.Letuscreateanenumthatwillshowthepossiblewaysto

    exitfromahouse:

    enumexitDoor{

    caseDoor1

    caseDoor2

    caseDoor3

  • caseDoor4

    }

    Thevaluesinside{}(curlybraces)arecalledthemembervalues.Todefinethemember

    valuesinanenum,weusethecasekeyword.Thisshowsthatanewlinefordefininga

    memberoftheenumhasbeenstarted.Theenumabovewillcontainonlythelistedabove

    asmembers.Otherthandefiningthemindividually,theycanbedefinedinasingleline,

    andyouseparatethemwithacommaasfollows:

    enumExitDoor{

    caseDoor1,Door2,Door3,Door4

    }

    Noticethatthenameofeverymemberstartswithacapitalletter.Tousetheenumeration

    above,wecandoasfollows:

    VarjohnExitedThroughDoor=ExitedDoor.Door1

    Noticethatwedeclaredavariableandassignedavaluetothesamevariableatthesame

    time.Again,ifyouwerekeenonautoComplete,yourealizedthatitgavetheoptionsof

    onlyfourdoors.Thisisoneofthewaysusedinenumstoensureaccuracy.

    Apartfromthemethodmentionedabove,wecanalsousethisone:

  • varmaryExitedThroughDoor:ExitedDoor

    maryExitedThroughDoor=.Door2

    Itisveryclearthatfromthesecondmethod,wehaveusedspecificationsoastosetthe

    value.Letusdemonstratetheuseofswitchstatementtoaccessthevaluesofanenum:

    switchjohnExitedThroughDoor{

    case.Door1:

    println(HeusedDoor1)

    case.Door2:

    println(HeusedDoor2)

    case.Door3:

    println(HeusedDoor3)

    case.Door4:

    println(He4usedDoor)

    }

    TheoutputontheplaygroundwillshowthatDoor1wasused.Noticewehavespecifieda

    caseforeverymemberoftheenum,asfailuretodosowillresultintoanerror.Youcan

    deleteoneofthecasestatementsaboveandseewhatwillhappen.Thecompilerwilltell

    thatyourcodehasaproblem.

  • EnumAssociatedValuesinSwift

    Withassociatedvalues,extrainformationcanbeaddedtoeachvalueoftheenum.These

    valuescanbeofanytype.Todemonstratethis,considertheenumshownbelow:

    enumAssociationDemo{

    caseName(String)

    caseNums(Int,Int,Int)

    }

    Wehavedefinedtwocasestatements,onetoholdastringandtheotheronetoholdthree

    valuesoftypeinteger.Letusdefinetwovariablesasshownbelow:

    varname=AssociationDemo.Name(John)

    varexampleNums=AssociationDemo.Nums(4,13,17)

    Letustocheckthevaluesusingaswitchstatement:

    switchname{

    case.Name(letname):

    println(Thenameis\(name))

    case.Nums(letval1,letval2,letval3):

  • println(Thevalueofinteger1is\(val1))

    println(Thevalueofinteger2is\(val2))

    println(Thevalueofinteger3is\(val3))

    }

    Nowwehaveaccessedthevalues.Westartedbyaccessingthename,andthenlastlywe

    accessedtheintegers.Everyvalueoftheenumhasbeenprovidedwithacase.

  • RawValues

    Withrawvalues,youareabletodeclarevaluesinsidetheenum.Itworksjustinthe

    oppositewayasassociatedvalues,sincetheseallowyoutodeclarevaluesoutsidean

    enum.Thetypeofenumerationtousethetechniquemustbespecified.

    enumEnum2:String{

    caseName=John

    caseWebSite=http://www.john.com

    }

    varname=Enum2.Name

    varebsite:Enum2

    website=.WebSite

    Notethesyntaxwehaveusedtoaccessthevalues.Veryeasy.Youshouldknowhowto

    handleenumswithoutvalues,asyoumighttrytoaccessemptyvalues.

    //Nowletsaccessthosevaluesusingthehandy.Raw()

    myName.toRaw()//OutputsPeter

    myWebsite.toRaw()//Outputshttp://www.peterwitham.com

  • Chapter7:

    UIAlertViewinSwift

    AnalertviewcanberepresentedasfollowsusingiOS8SDKandSwift:

    varalt=UIAlertController(title:TitleoftheAlert,message:Themessage

    ofthealert,preferredStyle:UIAlertControllerStyle.Alert)

    alt.addAction(UIAlertAction(title:OK,style:UIAlertActionStyle.Default,

    handler:nil))

    self.presentViewController(alt,animated:true,completion:nil)

    ThestylecanalsobesettoeitherDestructiveorCancelifneeded.

  • Chapter8:

    NSTimerinSwift

    Ouraiminthischapteristocreateacounterapplication,anditwillmakeuseoftheSwift

    NSTimerclass.ThisclasscanbeusedtocreateatimeriniOS8applications.Itfunctions

    bywaitingforaspecificintervaloftimetoelapsesothatitcanfire.

    Onceitfires,amessageisalwaystotheSwiftobjectwhichistargeted.Agoodexampleis

    theschedulingofupdates,wherebythetimercanbeusedtotriggerthisataspecifictime.

    Tocreatesuchanapp,theprojectneedstobesetupinaspecificmanner.

  • ProjectSetup

    Createanewapplication(SingleView)andgiveitanameofyourchoice.Wethenneedto

    addsomeelementstotheMain.storyboard.ThesewillbeobtainedfromtheobjectLibrary

    inXcode.Theseelementsincludeanavigationbar,toolbar,UILabel,BarButton,Itemx2,

    andaflexibleSpaceBarButtonItem.

    AddingtheToolbar

    Beginbydraggingthistotheprojectsbottom:

    ClickontheItembuttonandgotothepropertyinspector.Chooseplay:

  • TheItemwillchangetoaplayicon,andthetoolbarwillbeasfollows:

    AddingtheFlexibleSpaceBarButtonItem

    Thepurposeofthisistospaceoutthebarbuttonitems.Ontopofthetoolbarlocatedat

    theprojectsbottompart,dragthisitem:

  • Item1ofBarButton

    Dragthistothebottomandleftofyourtoolbar.Itshouldlookasfollows:

    NavigationBar

    Ontopoftheviewcontroller,dragthenavigationbar.AvoidoverlappingtheiPhone

    batterybynotplacingthenavigationbarrightatthetop.DoubleclickthewordTitle,

    andrenameittosomethingelseofyourchoice.Inmycase,IwillrenameittoNSTimer

    Tutorialsoitshouldlookasfollows:

    Item2ofBarButton

    Addanotherbarbuttononthenavigationbydraggingit.Placeittotheright.Doubleclick

    ontheItemandchangeittoClear.

  • UILabel

    Ontotheviewcontroller,dragthisitem.Placeitatthemiddleoftheproject.Fromthe

    propertyinspector,editthelabelalignment,size,andcolor(optional).Doubleclickonthe

    wordLabel,andchangeitto0(zero).

  • Theinterfaceisnowsetup.Thenextthingistostartcodingsoastoaddthenecessary

    functionalitytothetimer.

  • Codingthetimer

    SelectthefileViewController.swiftfromthenavigationareaoftheproject.Thisiswhere

    codingshouldbedonetoaddfunctionalitytotheNSTimer.Todefinethetimer,weneed

    todothisbetweenthefollowinglinesofcode:

    classViewController:UIViewController{

    overridefuncviewDidLoad(){

    WedefineourfirstvariabletmfortimerwhichisoftypeNSTimerasfollows:

    vartm=NSTimer()

    Abovethedeclarationabove,weshoulddefinethecounterandinitializeitto0asfollows:

    varcounter=0

    AtthemiddleofthestoryboardandontheUILabel,presstheCtrlkeyanddragtoyour

    viewcontrollerfile.NameitCountingLabel.

  • ChecktheViewController.swiftfiletoseeifithasthefollowingcode:

    @IBOutletvarcountingLabel:UILabel!

    Repeatthesameprocedurefortheotherbuttons,butthistime,makesureyouchoosethe

    connectiontypeAction.Afterdoingthat,thefollowingcodeshouldbeaddedtoyour

    project:

    @IBActionfuncstartButton(sender:AnyObject){}

    @IBActionfuncpauseButton(sender:AnyObject){}

    @IBActionfuncclearButton(sender:AnyObject){}

    ValuescanthenbeaddedtotheCountingLabel.NotethattheUILabelisastring,whereas

    thecounterisaninteger.Theoutputmustbeconvertedtoastringbeforeaddingittothe

    label.Thiscanbedoneasfollows:

    countingLabel.text=String(counter)

    Itstimetostartthetimer.ThiscanbedonebyaddingthisfunctionalitytothestartButton

  • asfollows:

    tm=NSTimer.scheduledTimerWithTimeInterval(TIME_INCREMENT,target:self,

    selector:Selector(FUNCTION),userInfo:nil,repeats:BOOL)

    Rememberthatwecreatedvariabletmearlieron,andwhatwedoneinthiscaseis

    assigninganewinstanceofNSTimertothis.Notethatwehaveaddedsomenewthingsas

    explainedbelow:

    1.TIME_INCREMENT-specifiesthenumberofsecondsafterwhichthetimer

    fires.Wewillsetthisoneto1.

    2.FUNCTION-thisisafunctiontobecreated,anditwillbetriggeredwhen

    thefiringtimeisreached.

    3.BOOL-ifthevalueofthisissettoYES,itwillkeeponreschedulingitself

    untilitisinvalidated.Afterfiring,thetimerwillbeinvalidatedifthisvalueissetto

    NO.

    Theabovelineofcodethenbecomes:

    tm=NSTimer.scheduledTimerWithTimeInterval(1,target:self,selector:

    Selector(counterUpdator),userInfo:nil,repeats:true)

  • Wehavedeclaredafunctionintheabovelineofcode.Weneedtocreateitanduseitfor

    thepurposeofincrementingthevalueofthecounterby1.Assumingthatyouknowthe

    incrementoperator,thatis,++,letususethis,anditwillincrementthisvalueby1.This

    willhappeneverytimethisfunctioniscalled.Thiswillthenbecome:

    FunccounterUpdator(){

    countingLabel.text=String(counter++)

    }

    Youcannowrunyourapp.Onceyouclickonstart,youwillrealizehowmuchyouhave

    achievedwithlesscoding.

  • StoppingtheNSTimer

    ThemethodInvalidate()isusedtopauseorstoptheNSTimer.Weneedtoaddsome

    functionalitytotheIBActionofthepausebuttonasshownbelow:

    @IBActionfuncstopButton(sender:AnyObject){

    tm.invalidate()

    }

    Nowyoucanplayaroundwiththetimerbystartingitandpausingit.

  • ClearingtheNSTimer

    Forustoclearthecounter,thefollowingneedstobedone:

    1.PausetheNSTimerfromfiring.

    2.Resetthecountertonormal.

    3.ClearthecountingLabel.

    Notethattheaboveordermustbeadheredto,otherwisetheobjectivewillnotbeachieved.

    ThefollowingshouldbetheappearanceoftheIBActionoftheclearButton:

    @IBActionfuncclearButton(sender:AnyObject){

    tm.invalidate()

    counter=0

    countingLabel.text=String(counter)

    }

    Youcannowrunyourapp.Everyfeaturethatwewantedhasworked,sowearedone.The

    timerhasbeencreatedwithSwiftandNSTimer.ThisshowshowmuchSwiftcanbeused

    todevelopamazingappsforiOS8devices.Moreso,usingintegersandstringsshouldnot

    bea=nissuetoyounowasyouhavelearnedhowtousethem.

  • Chapter9:

    SwiftandPHP

    ItispossibletouseSwifttosendsomepostrequesttoaPHPscript.Thishappensona

    server.IfyouconnectyourSwiftapptoaPHPwebservice,youwillachieve

    functionalitiessuchasqueryingthedatabaseandevenregisteringtheusers.

    Therearealsomanyfeaturesthatyoucanenjoy.Thereexistservicesthatcanhelpyouin

    achievingthis.ProgrammerswithoutaccesstoaPHPwebserviceorthosewhocannot

    createoneforthemselvescanusetheseservices.

    Inthissection,wewilluseParse.comforthispurpose.ItusesHTTP(HyperTextTransfer

    Protocol)requestcodestodeterminewhethertherequeststhatyousendsucceededor

    failed.Thesecodesarenumerous,andeachisusedforaspecificpurpose,soyoucanfind

    tutorialsabouttheseonline,andusetherightone.Wewillusethecode200whichtellsus

    thatourconnectionsucceeded,andthenwewillbeabletosucceed.

    SetupanewSwiftprojectonXcode6.OntotheMain.storyboard,dragabutton.Linkitas

    anIBActiontotheviewController,andgiveitanameofyourchoice.Thenextthingisto

    addfunctionalitytothisbutton.Thiscanbeachievedbyuseofafunction.Iwillcallmy

    functionsendFunction.TheviewController.Swiftshouldbeasfollows:

  • importUIKit

    classViewController:UIViewController{

    funcsendFunction(){

    println(ButtonPressed)

    }

    @IBActionfuncsendButton(sender:AnyObject){

    sendFunction()

    }

    overridefuncviewDidLoad(){

    super.viewDidLoad()

    //addanyadditionsetupaftertheviewisloaded.

    }

    overridefuncreceivedMemWarning(){

    super.receivedMemWarning()

    //anyresourceswiththeabilitytobecreatedshouldbedisposed.

    }

    }

    TheButtonPressedmessagewillbedisplayedontheconsolelinearea.Incaseyouneed

    tobeemailedwhenthereisapostrequest,youcanusethePHPcodebelow:

    $reqVar=$_POST[data];

    if(!empty($reqVar)){

  • mail([email protected],emailsubject,PostsetandButtonpressed);

    }

    Ifyouwanttoallowsomeonetoaccessyourserver,orifyouareconnectingtoadatabase,

    makesurethatyouarecarefulsoastoavoidmaliciousattacks.

  • PostingfromSwifttoPHP

    Declarethefollowingtwovariablesinyourfunction:

    varu:NSURL=NSURL(string:http://url.com/path/to/file.php)!

    varrqst:NSMutableURLRequest=NSMutableURLRequest(URL:url)

    Belowtheabovelinesofcode,addthefollowing:

    varbData=data=something

    Foryoutospecifythemethodthatwearesendingin,addthefollowingcode:

    rqst.HTTPMethod=POST

    Wethenneedtoputtogetheralltheabove,andsendtotheserverasone.Thiscanbedone

    asfollows:

    rqst.HTTPBody=bodyData.dataUsingEncoding(NSUTF8StringEncoding);

    NSURLConnection.sendAsynchronousRequest(rqst,queue:

    NSOperationQueue.mainQueue())

  • {

    (response,data,error)in

    println(response)

    }

    Afterrunningtheappatthistime,aresponsewillbeseenintheconsolelog.Itwillhave

    theentireresponse.

  • HowtoGettheStatusoftheHTTPCode

    Intheabovecase,regardlessofwhetherthescriptssucceedsorfails,theuserwillbe

    directedtotheViewController.WewanttodirecttheusertoanewViewControllerifthe

    connectionexistsandthescriptrunscorrectly.Anifstatementistherightchoicehere,and

    weshouldcombineitwiththecode200.Thiscanbedoneasfollows:

    ifletHTTPResponse=responseas?NSHTTPURLResponse{

    letsCode=HTTPResponse.statusCode

    ifsCode==200{

    //Thendosomething.

    }

    }

    Youcannowrunyourapp.YounowknowhowtoposttoaPHPscriptfromSwift.We

    havealsousedastatuscodetocheckwhetherthiswentoncorrectly.

  • Chapter10:

    ConnectingtoiTunesSearchAPI

    Inthischapter,youwillknowhowtoconnecttotheiTunessearchAPIusingSwift,

    downloadtheJSONresults,andparsethemtothedictionaries.Thisinformationwillthen

    beusedtopopulatethetableviews.Aclickeventwillthenbeaddedtothetableviewfor

    thesakeofuserinteraction.Onclickingthisitem,theiTunesstorewillbeopened.

  • HowtoConnecttheUserInterface

    Weshouldbeginbygettingareferencetothetableview.IntheViewController.swiftjust

    outsideotherfunctionsandafterclassdefinition,addthefollowingcode:

    @IBOutletvarappTV:UITableView

    ThevariableappTVwillmakeitpossibletoconnecttotheTableViewinthestoryboard.

    Savethefileabove.

    Openthestoryboard.DragfromtheTableViewtotheViewcontrollerobject.Thiswill

    linktheseobjects.

  • HowtoMaketheAPIRequest

    Sincewehaveconnectedtheuserinterface,wecanmaketheAPIcall.Createanew

    function,andgiveitanameofchoice.IhavecalledmineiTunesSearch(searchterm:

    String).Aftersearchingarbitraryterms,thiswillcausetherequesttohappen.Writethe

    codebelow:

    funciTunesSearch(term:String){

    //replacespaceswith+symbol.

    variTunesTerm=term.stringByReplacingOccurrencesOfString(,withString:+,

    options:NSStringCompareOptions.CaseInsensitiveSearch,range:nil)

    //anythingthatisURLfriendlyshouldbeescaped

    varescapedTerm=

    iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    varpath=https://itunes.apple.com/search?term=\(escapedTerm)&media=software

    varurl:NSURL=NSURL(string:path)

    varrqst:NSURLRequest=NSURLRequest(URL:url)

    varctn:NSURLConnection=NSURLConnection(rqst:rqst,delegate:self,

    startImmediately:false)

    println(URLforsearchingiTunesAPI\(url))

    ctn.start()

    }

    Wehavestartedbyfixingthesearchtermthatwepassin.TheiTunessearchAPi

  • recommendsthattermsshouldbeoftheformfirst+second+third+words.This

    contradictstheformfirst%20cecond%20.ThisiswhywehaveusedanNSStringmethod,

    thatis,stringByReplacingOccurencesOfString.

    Thesearchtermwillbemodifiedbyreplacingalltheavailablespaceswitha+symbol.

    Youcanalsoseetheescape,whichwillmakeitpossibletoescapethesearchtermifa

    symbolthatcannotfitintheURLisfound.WehavealsodefinedanNSURL,whichcan

    beusediniOS8snetworkAPIasaRequestURL.Thelinesbelowasusedabovearevery

    important:

    varrqst:NSURLRequest=NSURLRequest(URL:url)

    varctn:NSURLConnection=NSURLConnection(rqst:rqst,delegate:self,

    startImmediately:false)

    ThefirstlinehasusedtheurlthatwecreatedasthetargetURLtocreatean

    NSURLRequestobject.Thesecondlinehasdonethemainjobbycreatingaconnection

    whichistobeusedforsendingtherequest.Thepurposeofsettingthedelegatetoselfisto

    beabletolistentotheinformationthatwillcomefromtheconnectioninsidetheview

    controllerclass.Tobegintherequest,wehaveusedctn.start().

  • HowtoPreparefortheResponse

    NowthatwehavesenttheRequest,weneedtopreparefortheresponsethatwewillget.

    AttheendofviewDidLoad,addthefollowingcode:

    iTunesSearch(JPSoftware)

    JPSoftwareisoursearchterm,sothefunctionwillsearchforanysoftwareintheiTunes

    storewhichcontainsthatphrase.Youcanchangethesearchtermtowhatyouwanttolook

    forfromtheiTunesstore.Adataobjecttocontaintheresultsisneededforustogetthe

    results.LetuscreateaninstanceofNSMutableDataasaclassmember.Insidethecurly

    braceandjustbelowtheclassdefinition,addthefollowinglineofcodetoachievethis:

    vard:NSMutableData=NSMutableData()

    vartData:NSArray=NSArray()

    Nowwearepreparedtoreceivetheresponse.Itistimetoreceiveit.Addthefollowing

    chunkofcode:

    funcctn(receivedResponse:NSURLConnection!,receivedResponseresponse:

    NSURLResponse!){

    //clearoutthedataobjectifanewrequestwasreceived.

  • self.d=NSMutableData()

    }

    funcctn(ctn:NSURLConnection!,receivedDatad:NSData!){

    //addthereceiveddatatothedataobject

    self.d.appendData(d)

    }

    funcctnFinishedLoading(ctn:NSURLConnection!){

    //self.dshouldholdtheresultinginfo,requestiscomplete

    //receiveddataisconvertedintoanobjectthroughJSONdeserialization

    varerr:NSError

    varjResult:NSDictionary=NSJSONSerialization.JSONObjectWithData(d,options:

    NSJSONReadingOptions.MutableContainers,error:nil)asNSDictionary

    ifjResult.count>0&&jResult[results].count>0{

    varresults:NSArray=jResult[results]asNSArray

    self.tData=results

    self.appsTableView.reloadData()

    }

    }

    TheNSURLconnectionreceivestheresponse,andthenitwillcalltherecivedResponse

    method.Anewandemptyobjectwillbeinthelineself.d=NSMutableData().Oncethe

    connectionisestablished,datawillbereceivedthroughthemethodreceivedData().The

    importantinformationhereistheargumentpassedinthemethod.Everychunkofdatais

    important,andthatiswhywehaveusedself.dtoappendit.

  • NotethatwehaveusedthectnFinishedLoading()methodinthefinalstep.Thisisafterthe

    connectionhasbeenestablishedandallthedatahasbeenreceived.Wecanthenusethe

    receiveddatainourapp.TheNSJSONSerializationconvertsthereceiveddataintodata

    dictionaryobjectswhichareuseful.Thisisachievedbydeserializationoftheresultsfrom

    iTunes.

    Thefinalprocessinvolvesvalidatingtheresultssoastocheckonwhethertheyarewhat

    weexpected.Theresultingdatacanthenbesettothetabledatabyself.tDataobject.The

    appsTableViewreloadsitscontent.

  • HowtoUpdatetheTableViewUI

    Rememberthatthetableviewhastwofunctions,acellfunctionforcreationand

    modificationofcellsforeachrowandacountfunctionwhosepurposeistocountthe

    numberofrows.Weneedtoputthedataweobtainedfromthewebintothetable.

    Considerthecodebelow:

    functView(tableView:UITableView!,numberOfRowsInSectionsection:Int)->Int{

    returntData.count

    }

    functView(tView:UITableView!,cellForRowAtIndexPathindexPath:NSIndexPath!)->

    UITableViewCell!{

    letcell:UITableViewCell=UITableViewCell(style:UITableViewCellStyle.Subtitle,

    reuseIdentifier:CellforTesting)

    varrData:NSDictionary=self.tData[indexPath.row]asNSDictionary

    cell.text=rData[trackName]asString

    //GrabbingtheartworkUrl60keyforgettingimageURLforthethumbnailoftheapp

    varuString:NSString=rData[artworkUrl60]asNSString

    variURL:NSURL=NSURL(string:uString)

    //DownloadrepresentationoftheimageasNSDataattheURL

    variData:NSData=NSData(contentsOfURL:iURL)

    cell.image=UIImage(data:iData)

    //obtaintheformattedpricestringtobedisplayedonthesubtitle

    varfPrice:NSString=rData[fPrice]asNSString

  • cell.detailTextLabel.text=fPrice

    returncell

    }

    numberOfRowsInSectionwillreturnthenumberofresultingobjectsfromthetableData

    member.ThisissettothectnFinishedLoadingmethod.Therownumberhasbeentograb

    threevalues,sowedontreturntherownumberbutthethreevalues.Thesethreekeysare

    thenusedtoconstructthetitle,thesubtitle,andtheimagethatwillbeputalongthecell.

    TheViewController.swiftshouldlookasfollows:

    importUIKit

    classViewController:UIViewController,UITableViewDataSource,

    UITableViewDelegate,NSURLConnectionDelegate,NSURLConnectionDataDelegate{

    @IBOutletvarappsTableView:UITableView

    vardata:NSMutableData=NSMutableData()

    vartData:NSArray=NSArray()

    overridefuncviewDidLoad(){

    super.viewDidLoad()

    iTunesSearch(AngryBirds);

    }

    funciTunesSearch(term:String){

    //replacespaceswith+symbol.

    variTunesTerm=term.stringByReplacingOccurrencesOfString(,withString:+,

  • options:NSStringCompareOptions.CaseInsensitiveSearch,range:nil)

    //AnythingwhichisnotURL-friendlyisescaped

    varescapedTerm=

    iTunesTerm.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    varuPath=https://itunes.apple.com/search?term=\

    (escapedTerm)&media=software

    varurl:NSURL=NSURL(string:uPath)

    varrqst:NSURLRequest=NSURLRequest(URL:url)

    varctn:NSURLConnection=NSURLConnection(rqst:rqst,delegate:self,

    startImmediately:false)

    println(URLforsearchingiTunesAPI\(url))

    ctn.start()

    }

    functView(tView:UITableView!,numberOfRowsInSectionsection:Int)->Int{

    returntData.count

    }

    functView(tView:UITableView!,cellForRowAtIndexPathindexPath:NSIndexPath!)

    ->UITableViewCell!{

    letcell:UITableViewCell=UITableViewCell(style:UITableViewCellStyle.Subtitle,

    reuseIdentifier:CellforTesting)

    varrData:NSDictionary=self.tData[indexPath.row]asNSDictionary

    cell.text=rData[trackName]asString

    //GrabbingtheartworkUrl60keyforgettingimageURLforthethumbnailoftheapp

    varuString:NSString=rData[artworkUrl60]asNSString

    variURL:NSURL=NSURL(string:uString)

    //DownloadrepresentationoftheimageasNSDataattheURL

  • variData:NSData=NSData(contentsOfURL:iURL)

    cell.image=UIImage(data:iData)

    //obtaintheformattedpricestringtobedisplayedonthesubtitle

    varfPrice:NSString=rData[fPrice]asNSString

    cell.detailTextLabel.text=fPrice

    returncell

    }

    }

    funcctn(receivedResponse:NSURLConnection!,receivedResponseresponse:

    NSURLResponse!){

    //clearoutthedataobjectifanewrequestwasreceived.

    self.d=NSMutableData()

    }

    funcctn(ctn:NSURLConnection!,receivedDatad:NSData!){

    //addthereceiveddatatothedataobject

    self.d.appendData(d)

    }

    funcctnFinishedLoading(ctn:NSURLConnection!){

    //self.dshouldholdtheresultinginfo,requestiscomplete

    //receiveddataisconvertedintoanobjectthroughJSONdeserialization

    varerr:NSError

    varjResult:NSDictionary=NSJSONSerialization.JSONObjectWithData(d,options:

    NSJSONReadingOptions.MutableContainers,error:nil)asNSDictionary

    ifjResult.count>0&&jResult[results].count>0{

    varresults:NSArray=jResult[results]asNSArray

    self.tData=results

  • self.appsTableView.reloadData()

    }

    }

    }

    }

    }

    Nowtheappisreadyforrunning,sodoso.OursearchtermwasAngryBirds,sothe

    followingwillbeobtainedastheresult:

  • Chapter11:

    ImageLoadingandCachingAsynchronously

    Ouraimistoaccessimagesstoredinthecache.Iftheydontexistinthecache,weshould

    downloadthemwhileonabackgroundthread.Ifanimagehasbeendownloaded,we

    shouldnotdownloaditagain,sinceitwillbestoredinthecacheandhencebeaccessible

    fromthere.Considerthecodebelow:

    functView(tView:UITableView,cellForRowAtIndexPathindexPath:NSIndexPath)->

    UITableViewCell{

    letcell:UITableViewCell=tView.dequeueReusableCellWithIdentifier(kCellIdentifier)

    asUITableViewCell

    varrData:NSDictionary=self.tData[indexPath.row]asNSDictionary

    //makingsurethatitexists

    letcellText:String?=rData[trackName]as?String

    cell.textLabel?.text=cellText

    cell.imageView?.image=UIImage(named:B52)

    //obtaintheformattedpricestringforthesubtitlebeingdisplayed.

    letfPrice:NSString=rData[fPrice]asNSString

    letuString=rData[artworkUrl60]asString

  • //Checkthecacheforexistingkey.

    letuString=rData[artworkUrl60]asString

    //checkingtheimagecacheforakey

    varimg=self.imageCache[uString]

    if(img==nil){

    //downloadtheimageifitisnotexisting

    varimgURL:NSURL=NSURL(string:uString)

    //DownloadingNSDatarepresentationoftheimage

    letrqst:NSURLRequest=NSURLRequest(URL:imgURL)

    NSURLConnection.sendAsynchronousRequest(rqst,queue:

    NSOperationQueue.mainQueue(),completionHandler:{(response:NSURLResponse!,d:

    NSData!,error:NSError!)->Voidin

    iferror==nil{

    img=UIImage(data:d)

    //Storingtheimageinthecache

    self.imageCache[uString]=img

    dispatch_async(dispatch_get_main_queue(),{

    ifletcToUpdate=tableView.cellForRowAtIndexPath(indexPath){

    cToUpdate.imageView?.image=img

    }

    })

    }

  • else{

    println(Error:\(error.localizedDescription))

    }

    })

    }

    else{

    dispatch_async(dispatch_get_main_queue(),{

    ifletcToUpdate=tView.cellForRowAtIndexPath(indexPath){

    cToUpdate.imageView?.image=img

    }

    })

    }

    cell.detailTextLabel?.text=fPrice

    returncell

    }

    Wehavefirstsetthecellsplaceholderimagebeforedownloadingtheimage.Createan

    image,andimportittoyourprojectjustbyCtrl+drag.NameitB52.Setthecellstouse

    thisimage.Wealsocheckedtheimagecacheforthepresenceoftheimage.

    ThemethodsendAsynchronousRequestwilltakeaclosure/functionasaparameter.We

    havecheckedforthepresenceofanerror,andifitdoesntexist,wewillcreateanimage

  • fromthedatad.Thelineself.imageCache[uString]=imghasthepurposeofsavingthe

    imageintheimagecache,anditwillusetheimageURLasthekey.OntheUIthread,we

    havesetthecellimage.

    Youcannowruntheapp,andobservetheoutput.Thetableviewwillbeverysmooth.

  • Chapter12:

    UsingObjective-CclassesinSwift

    Youmightneedtouseoftheobjective-CclassesinSwift.Thisispossible.Justdothe

    following:

    1. Add.m(Objective-Cimplementation)

    Thisfile,thatis,a.mone,shouldbeaddedtotheclassandnamedCustomObject.m

    2. AddtheBridgingHeader

    Duringtheadditionofthe.mfile,adialogwillappearwhichlooksasfollows:

    JustclickonYes.

    3. Add.h,theObjective-CHeader

    Addanother.h.GiveitthenameCustomObject.h

  • 4. BuildtheObjective-Cclass

    InCustomObject.h,thisshouldbeasfollows:

    #import

    @interfaceCustomObject:NSObject

    @property(strong,nonatomic)idaProperty;

    -(void)aMethod;

    @end

    InCustomObject.m,tshouldbeasfollows:

    #importCustomObject.h

    @implementationCustomObject:NSObject

    -(void)aMethod{

    NSLog(@aMethodRan);

    }

    @end

    5.AddaclasstotheBridging-Header

    Thisshouldbe:

    #importCustomObject.h

    6.UseyourObject

  • variOfObject:CustomObject=CustomObject()

    iOfObject.aProperty=HelloWorld

    println(iOfObject.aProperty)

    iOfObject.aMethod()

    Thebridgingheaderissousefulsincewithit,thereisnoneedtoimportexplicitly.Youare

    done,soyoucansafelyusetheclasses.

  • Chapter13:

    AnimationsinSwift

    WithSwift,onecancreateanappwithanimations.Thiscanbeachievedasfollows:

  • ContainerViewTransitions

    Ifyouwanttoperformananimatedtransitionbetweenviews,performthistransitionina

    parentcontainer.Intheexamplebelow,wearegoingtoperformananimatedtransition

    betweentwoUIViewswhicharecolored.Thecontaineroftheanimationwillbethethird

    UIView.LetusstartbysettingupthreeviewsintheviewDidLoad()function:

    letcner=UIView()

    letrSquare=UIView()//red

    letbSquare=UIView()//blue

    overridefuncviewDidLoad(){

    super.viewDidLoad()

    //settingthecontainerframeandaddingittothescreen

    self.cner.frame=CGRect(x:60,y:60,width:200,height:200)

    self.view.addSubview(cner)

    //settinguptheredframe

    //boththeredandbluesquareframesshouldbelocatedatthesameposition

    //wethenjustreuserSquare.frame

    self.rSquare.frame=CGRect(x:0,y:0,width:200,height:200)

    self.bSquare.frame=rSquare.frame

    //setbackgroundcolors

  • self.rSquare.backgroundColor=UIColor.redColor()

    self.bSquare.backgroundColor=UIColor.blueColor()

    //letusjustaddtheredsquareforthistime.Thebluesquarewillbeaddedlaterin//the

    animation.

    self.container.addSubview(self.rSquare)

    }

    Justruntheapp.Aredsquarewillbetheoutput.

    Nowtoachievetheanimationbetweenthetwosquares, letscreateadda@IBActionto

    thebuttoninthestoryboard:

    @IBActionfuncaButtonTapped(sender:AnyObject){

    //createapairofmoreobjectsandassignthemtoasinglevariable(tuple)

    letvws=(frontView:self.rSquare,backView:self.bSquare)

    //setthestyleofthetransition

    lettOptions=UIViewAnimationOptions.TransitionCurlUp

    UIView.transitionWithView(self.cner,duration:1.0,options:tOptions,animations:{

    //removingthefrontobject

    vws.frontView.removeFromSuperview()

    //addingtheotherobject

    self.cner.addSubview(vws.backView)

    },completion:{finishedin

    //oncetheanimationhascompleted,anycodeaddedherewillbeapplied

  • })

    }

    After running theapp,youwillnotice thatwewillgetstuckwith thebluesquare.Lets

    solvethisbyaddingsomelogiccodewhichwillcheckthevisiblesquare:

    //createapairofmoreobjectsandassignthemtoasinglevariable(tuple)

    varvws:(frontView:UIView,backView:UIView)

    //ifrSquarehasasuperView,example,itisinthecontainer,

    //setitasfront,andbSquareasback

    //otherwise,dofliptheorder

    if(self.rSquare.superview){

    vws=(frontView:self.rSquare,backView:self.bSquare)

    }

    else{

    vws=(frontView:self.bSquare,backView:self.rSquare)

    }

    Thetransitionwillthenbeaddedasfollows:

    @IBActionfuncaButtonTapped(sender:AnyObject){

    varvws:(frontView:UIView,backView:UIView)

    if(self.rSquare.superview){

  • vws=(frontView:self.rSquare,backView:self.bSquare)

    }

    else{

    vws=(frontView:self.bSquare,backView:self.rSquare)

    }

    //settingupthetransitionstyle

    lettOptions=UIViewAnimationOptions.TransitionCurlUp

    UIView.transitionFromView(vws.frontView,toView:vws.backView,duration:1.0,

    options:tOptions,completion:nil)

    }

    Theabovewilloutputauniquetransition:

  • Theredviewwillbechangedtoblue.Youcanalsochoosetosetthetransitiontoanystyle

    ofchoicesuchas:

    lettOptions=UIViewAnimationOptions.TransitionFlipFromLeft

  • Chapter14:

    CreatinganAudioPlayerwithSwift

    Inthischapter,youwilllearnhowtocreateanaudioplayerwithSwift,comprisingofa

    playbutton,stopbutton,andasliderforvolumeadjustment.Wewillbeginbyaddingan

    audiofiletotheresourcesoftheproject.Ifyoudothis,anyaudioformatwillbe

    supported.

    Identifyanaudiofile,anddraganddropitintheSupportingfilesfolderofyourproject.I

    haveputanmp3audiocalledtest.mp3andIhaveputitintheaudiofilesfolderofmy

    project,sodothesame.

  • CreatingtheUserInterface

    Wewanttoaddthetwobuttonsandtheslider.JustselecttheMain.storyboardanddisplay

    theObjectLibrarybyView->Utilities->ShowObjectLibrary.Addthecomponentson

    theviewwindowbydraggingthemfromtheLibrary.Modifythemtolookasfollows:

    Selectthesceneviewwiththestoryboardcanvas.Getthelistofmenuoptionsbyselecting

    theAutoLayoutResolveAutoLayoutIssuesmenu.Selectreset.Fromtheviewcanvas,

    selectslider.DragthesliderjustbelowtheclassdeclarationintheAssistantEditor.Create

    anoutletconnectionandcallitvControlinthedialogthatwillappear.Dragtheplay

    buttontobelowtheviewDidLoad().EstablishanactionmethodnamedpAudioonthe

    TouchUpinside.

    DothesameforthestopbuttonandcalltheactionsAudio.Dragthesliderobjecttothe

    AssistantEditorpanelbeneaththecreatedactions.Fromthedialog,establishaconnection

    methodcalledadVolume.

  • SelecttheViewController.swiftfileafterclosingtheAssistantEditorpanel,andaddthe

    followingtoit:

    importUIKit

    importAVFoundation

    classViewController:UIViewController,AVAudioPlayerDelegate{

    @IBOutletweakvarvControl:UISlider!

    varaudioPlayer:AVAudioPlayer?

  • ActionMethods

    ImplementthefollowingmethodsintheViewController.swiftfile:

    @IBActionfuncpAudio(sender:AnyObject){

    ifletplyr=audioPlayer{

    plyr.play()

    }

    }

    @IBActionfuncsAudio(sender:AnyObject){

    ifletplyr=audioPlayer{

    plyr.stop()

    }

    }

    @IBActionfuncadVolume(sender:AnyObject){

    ifaudioPlayer!=nil{

    audioPlayer?.volume=vControl.value

    }

    }

  • CreationandInitializationofAVAudioPlayerObject

    AddthefollowingcodeintheviewDidLoad()methodoftheViewController.swiftfile:

    overridefuncviewDidLoad(){

    super.viewDidLoad()

    letu=NSURL.fileURLWithPath(

    NSBundle.mainBundle().pathForResource(test,

    ofType:mp3)!)

    vare:NSError?

    audioPlayer=AVAudioPlayer(contentsOfURL:u,e:&error)

    ifleterror=e{

    println(audioPlayererror\(error.localizedDescription))

    }else{

    audioPlayer?.delegate=self

    audioPlayer?.prepareToPlay()

    }

    }

  • ImplementationoftheAVAudioPlayerDelegateProtocolMethods

    Todothis,addthefollowingprotocolstotheViewController.swiftfile:

    funcaudioPlayerDidFinishPlaying(plyr:AVAudioPlayer!,succeeded

    flag:Bool){

    }

    funcaudioPlayerDecodeErrorDidOccur(plyr:AVAudioPlayer!,

    error:NSError!){

    }

    funcaudioPlayerBeginInterruption(plyr:AVAudioPlayer!){

    }

    funcaudioPlayerEndInterruption(plyr:AVAudioPlayer!){

    }

    Youcannowrunyourappandplayaroundwiththetwobuttonsandtheslider.

  • Conclusion

    It can be concluded that iOS 8 is used on Apple devices. Swift is the programming

    language developed recently for the purpose of creating iOS 8 apps. iOS 8 is superior

    comparedtothepreviousiOS7sinceitofferssomebetterfunctionalitiescomparedtothe

    latter.ForonetoprograminSwift,Xcode6needstobesetupfirst,andthisisaneasy

    task.

    Whileprogramming inSwift,Objective-Cclasses canbe imported to theSwift project.

    The vice versa is also true. This language has been used to create amazing apps for

    devices running iOS8whicharenowavailable in the iTunes store.These apps include

    coolfeaturessuchasplayingaudio,animations,andevenloadingimagesasynchronously.

    Book DescriptionIntroductionChapter 1: DefinitionChapter 2: Getting Started with iOS 8 Swift ProgrammingChapter 3: Variables and Constants in SwiftChapter 4: Type AnnotationsChapter 5: Tuples in SwiftChapter 6: Enumerations in SwiftRaw Values

    Chapter 7: UIAlertView in SwiftChapter 8: NSTimer in SwiftProject SetupCoding the TimerStopping the NSTimerClearing the NSTimer

    Chapter 9: Swift and PHPPosting from Swift to PHPHow to Get the Status of the HTTP Code

    Chapter 10: Connecting to iTunes Search APIHow to Connect the User InterfaceHow to Make the API RequestHow to Prepare for the ResponseHow to Update the Table View UI

    Chapter 11: Image Loading and Caching AsynchronouslyChapter 12: Using Objective-C classes in SwiftChapter 13: Animations in SwiftContainer View Transitions

    Chapter 14: Creating an Audio Player with SwiftCreating the User InterfaceAction MethodsCreation and Initialization of AVAudioPlayer ObjectImplementation of the AVAudioPlayerDelegate Protocol Methods

    Conclusion