Learning Iphone Programming From Xcode To App Store 1st Edition Alasdair Allan 2024 Scribd Download
Learning Iphone Programming From Xcode To App Store 1st Edition Alasdair Allan 2024 Scribd Download
com
https://ebookname.com/product/learning-iphone-programming-
from-xcode-to-app-store-1st-edition-alasdair-allan/
OR CLICK BUTTON
DOWNLOAD EBOOK
https://ebookname.com/product/learning-ios-programming-from-
xcode-to-app-store-third-edition-alasdair-allan/
https://ebookname.com/product/building-iphone-apps-with-html-css-
and-javascript-making-app-store-apps-without-objective-c-or-
cocoa-1st-edition-jonathan-stark/
https://ebookname.com/product/learning-iphone-game-programming-a-
hands-on-guide-to-building-your-first-iphone-game-1st-edition-
michael-daley/
https://ebookname.com/product/straight-a-s-are-not-enough-
learning-with-your-brain-turned-on-1st-edition-judy-fishel/
Basics Architectural Photography 1st Edition Michael
Heinrich
https://ebookname.com/product/basics-architectural-
photography-1st-edition-michael-heinrich/
https://ebookname.com/product/modeling-performance-
measurement-2005th-edition-wade-d-cook/
https://ebookname.com/product/the-concept-of-education-
international-library-of-the-philosophy-of-education-
volume-17-1st-edition-r-s-peters/
https://ebookname.com/product/listening-is-an-act-of-love-a-
celebration-of-american-life-from-the-storycorps-project-1st-
edition-dave-isay/
https://ebookname.com/product/interpreting-and-the-politics-of-
recognition-the-iatis-yearbook-1st-edition-christopher-stone/
Principles of Foundation Engineering Si Edition Braja
M. Das
https://ebookname.com/product/principles-of-foundation-
engineering-si-edition-braja-m-das/
Learning iPhone Programming
Learning iPhone Programming
Alasdair Allan
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions
are also available for most titles (http://my.safaribooksonline.com). For more information, contact our
corporate/institutional sales department: 800-998-9938 or [email protected].
Printing History:
March 2010: First Edition.
O’Reilly and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Learning iPhone
Programming, the image of a lapwing, and related trade dress are trademarks of O’Reilly Media, Inc.
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as
trademarks. Where those designations appear in this book, and O’Reilly Media, Inc. was aware of a
trademark claim, the designations have been printed in caps or initial caps.
While every precaution has been taken in the preparation of this book, the publisher and author assume
no responsibility for errors or omissions, or for damages resulting from the use of the information con-
tained herein.
TM
ISBN: 978-0-596-80643-9
[M]
1267461377
Table of Contents
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xi
1. Why Go Native? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
The Pros and Cons 1
Why Write Native Applications? 2
The Release Cycle 3
Build It and They Will Come 4
2. Becoming a Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Registering As an iPhone Developer 5
Enrolling in the iPhone Developer Program 7
The Apple Developer Connection 8
Installing the iPhone SDK 8
Preparing Your iPhone or iPod touch 11
Creating a Development Certificate 12
Getting the UDID of Your Development Device 14
Creating an App ID 15
Creating a Mobile Provisioning Profile 16
Making Your Device Available for Development 17
v
4. Coding in Objective-C . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Declaring and Defining Classes 41
Declaring a Class with the Interface 41
Defining a Class with the Implementation 42
Object Typing 43
Properties 44
Synthesizing Properties 45
The Dot Syntax 45
Declaring Methods 45
Calling Methods 46
Calling Methods on nil 47
Memory Management 47
Creating Objects 47
The Autorelease Pool 48
The alloc, retain, copy, and release Cycle 48
The dealloc Method 50
Responding to Memory Warnings 50
Fundamental iPhone Design Patterns 50
The Model-View-Controller Pattern 51
Views and View Controllers 51
The Delegates and DataSource Pattern 52
Conclusion 53
5. Table-View-Based Applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Simplifying the Template Classes 55
Creating a Table View 58
Organizing and Navigating Your Source Code 61
Connecting the Outlets 62
Building a Model 65
Adding Images to Your Projects 71
Connecting the Controller to the Model 73
Mocking Up Functionality with Alert Windows 74
Adding Navigation Controls to the Application 75
Adding a City View 79
Edit Mode 85
Deleting a City Entry 89
Adding a City Entry 90
The “Add New City...” Interface 93
Capturing the City Data 100
vi | Table of Contents
Tab Bar Applications 119
Refactoring the Template 120
Adding Another Tab Bar Item 122
Finishing Up 124
Modal View Controllers 125
Modifying the City Guide Application 126
The Image Picker View Controller 133
Adding the Image Picker to the City Guide Application 133
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Table of Contents | ix
Preface
The arrival of the iPhone changed everything. Or, at the very least, it changed the
direction of software development for mobile platforms, which is a pretty big thing. It
spawned an entire generation of copycat devices and shook an entire multibillion-dollar
industry to its knees. Despite this, it still fits in your pocket.
xi
What’s in This Book?
Here’s a short summary of the chapters in this book and what you’ll find inside:
Chapter 1, Why Go Native?
This chapter discusses the need for native applications and compares building
native applications to building web applications.
Chapter 2, Becoming a Developer
This chapter walks you through the process of registering as an iPhone developer
and setting up your work environment, from installing Xcode and the iPhone SDK
to generating the developer certificates you’ll need to build your applications and
deploy them onto your own iPhone or iPod touch.
Chapter 3, Your First iPhone App
This chapter allows you to get hands-on as quickly as possible and walks you
through building your first Hello World application, including how to deploy and
run the application on your iPhone or iPod touch.
Chapter 4, Coding in Objective-C
This chapter provides a crash course in the basics of the Objective-C language, and
if you’re familiar with another C-derived language (and perhaps with object-
oriented programming), it should be enough to get you up and running with
Objective-C and the Cocoa Touch frameworks.
Chapter 5, Table-View-Based Applications
The UITableView and associated classes are perhaps the most commonly used
classes when building user interfaces for iPhone or iPod touch applications. Due
to the nature of the applications, these classes can be used to solve a large cross
section of problems, and as a result they appear almost everywhere. In this chapter,
we dive fairly deeply into the table view classes.
Chapter 6, Other View Controllers
After discussing the table view controller in detail, we discuss some of the other
view controllers and classes that will become useful when building your applica-
tions: simple two-screen views, single-screen tabbed views, modal view controllers,
and a view controller for selecting video and images.
Chapter 7, Connecting to the Network
This chapter discusses connecting to the Internet, browsing the Web, sending
email, and retrieving information.
Chapter 8, Handling Data
This chapter discusses how to handle data input, both from the application user
and programmatically, and how to parse XML and JSON documents. The chapter
also covers storing data in flat files and storing data with the SQLite database
engine.
xii | Preface
Chapter 9, Distributing Your Application
This chapter talks about how to add some final polish to your application and
walks you through the process of building your application for distribution, either
via ad hoc distribution or for the App Store.
Chapter 10, Using Sensors
This chapter discusses how to determine what hardware is available and illustrates
how to deal with the major sensors on the iPhone and iPod touch: the
accelerometer, magnetometer, camera, and GPS.
Chapter 11, Geolocation and Mapping
This chapter walks you through the process of building applications that make use
of the Core Location and MapKit frameworks.
Chapter 12, Integrating Your Application
This chapter shows you some of the tricks to integrate your application with the
iPhone’s software ecosystem, how to present user preferences with Settings Bun-
dles, and how to use custom URL schemes to launch your application. It also
discusses how to make use of the Media Player and Address Book.
Chapter 13, Other Native Platforms
This chapter deals with the PhoneGap and MonoTouch platforms for building
native applications for the iPhone and iPod touch that can be sold on the App Store.
The chapter then walks you through the installation process and building your first
Hello World application for both platforms.
Chapter 14, Going Further
This chapter provides a collection of pointers to more advanced material on the
topics we covered in the book, and material covering some of those topics that we
didn’t manage to talk about in the book.
Preface | xiii
This icon signifies a tip, suggestion, or general note.
How to Contact Us
Please address comments and questions concerning this book to the publisher:
O’Reilly Media, Inc.
1005 Gravenstein Highway North
Sebastopol, CA 95472
800-998-9938 (in the United States or Canada)
707-829-0515 (international or local)
707-829-0104 (fax)
We have a web page for this book, where we list errata, examples, and any additional
information. You can access this page at:
http://oreilly.com/catalog/9780596806439
Supplementary materials are also available at:
http://www.learningiphoneprogramming.com/
xiv | Preface
To comment or ask technical questions about this book, send email to:
[email protected]
For more information about our books, conferences, Resource Centers, and the
O’Reilly Network, see our website at:
http://www.oreilly.com
Acknowledgments
Books do not write themselves, but a book is also not the work of just a single person,
despite what it may say on the front cover. I’d like to thank my editor, Brian Jepson.
His hard work and constant prodding made the book better than it might otherwise
have been. I’d also like to offer more than thanks to my long-suffering wife, Gemma
Hobson. Without her support, encouragement, and willingness to make those small
(and sometimes larger) sacrifices that an author’s spouse has to make, this book
wouldn’t be in your hands today. Thank you. Finally to my son, Alex, who is as yet too
young to do more than chew on the cover, daddy’s home. I can only hope for your sake
that O’Reilly uses tasty paper.
Preface | xv
CHAPTER 1
Why Go Native?
When the iPhone was introduced, there was no native SDK. Apple claimed that one
wasn’t needed and that applications for the device should be built as web applications
using JavaScript, CSS, and HTML. This didn’t go down well with the developer com-
munity; they wanted direct access to the hardware and integration with Apple’s own
applications.
Only a few months after the iPhone’s release, the open source community had accom-
plished something that many thought impossible. Despite Apple locking the device
down, developers had gained access, reverse-engineered the SDK, and gone on to build
a free open source tool chain that allowed them to build native applications for the
device. At one point, it was estimated that more than one-third of the iPhones on the
market had been “jail broken” by their users, allowing them to run these unsanctioned
third-party applications.
This open source development effort is ongoing today, and if you want to know more,
I recommend iPhone Open Application Development, Second Edition by Jonathan
Zdziarski (O’Reilly). However, the book you hold in your hands isn’t about the open
source “hacker” SDK, because in March 2008 Apple publicly changed its mind and
released the first version of the native SDK to a waiting developer community. Whether
this release was in response to this effort, or perhaps because it was (the notoriously
secretive) Apple’s plan all along, we’ll probably never know.
1
It seemed that the users of the applications disagreed. It’s arguable why this is the case,
but it’s very hard to make native-looking web applications that can be reused across
many different platforms, though it is possible. Just as applications on the Mac desktop
that have been ported from Windows tend to stand out like a sore thumb by not quite
working as the user expects, web applications, especially those that are intended to be
used across different platforms, tend to do the same.
If you integrate your application into the iPhone ecosphere, make use of the possibilities
that the phone offers, and optimize your user interface (UI) for the device, the user
experience is much improved. It’s also really hard to write web applications that work
well when you need to design for a smaller screen, implying as it does a simpler UI and
less exposed functionality, without using native controls.
Sometimes it’s not about doing things that can’t be done; it’s about doing things faster,
and doing client-side error handling. For instance, the Apple iTunes and App Store
applications that are provided with the iPhone are actually web applications wrapped
inside native applications. Just like the iTunes Store on the Mac, the main display you
see is a web page, but the surrounding infrastructure is a native application. This means
that while the application can’t do a lot without an Internet connection, it can at least
start up.
But those are extreme examples. A lot of the applications in the App Store combine
remote data and native interfaces. Without access to the network, some of the UI is
generally disabled. However, native applications can be built to degrade gracefully
when the device’s network connection disappears or if it was never present in the first
Before you start writing code, you need to do some housekeeping. First, you’ll need to
install Xcode, Apple’s development environment, as well as the iPhone SDK. Both of
these are available directly from Apple, although you may already have Xcode on your
Mac OS X install DVD. However, before you can install the iPhone SDK, you’ll have
to register with Apple as a developer. If you enroll in one of the developer programs,
you’ll also need to create, download, and install a number of certificates and profiles
to allow you to deploy your applications onto your iPhone or iPod touch. Let’s get these
housekeeping tasks out of the way now so that you can get to the interesting bit—the
code—as quickly as you can.
5
If you are an existing Apple Developer Connection (ADC) member, or
if you have an iTunes or MobileMe account, you can use your existing
Apple ID to register as an iPhone developer. However, if you intend to
sell software commercially, you may want to create a new identity for
use with the program to keep it separate from your existing Apple ID.
You’ll initially be asked to either choose an existing Apple ID or create a new one. If
you create a new one, you’ll be asked for some details (e.g., email and physical ad-
dresses); if you choose an existing Apple ID, you’ll still need to confirm some of these
details, although they should be filled in with the most recent information Apple has.
You’ll also be asked to provide a professional profile, indicating what sort of applica-
tions you’ll be developing and whether you also develop for other mobile platforms.
Finally, you’ll need to agree to the developer license. After you do, a verification code
may be sent to the email address you registered with Apple, although this doesn’t hap-
pen in all cases. However, if this happens to you, the final step of registering as an
iPhone developer will be to verify your email address.
Apple Websites
You’ll use four main websites as part of the iPhone development process:
The iPhone Dev Center
This site is where you can get access to the latest versions of the iPhone SDK, along
with background technical information, API documentation, sample code, and
instructional videos. You need to be a registered iPhone developer to access the site.
The Developer Program Portal
This site is where you can generate and manage the certificates, provisioning pro-
files, approved devices, and other housekeeping tasks necessary to test your ap-
plications on the iPhone and iPod touch and prepare them for distribution. You’ll
need to be both a registered iPhone developer and enrolled in one of the iPhone
Developer Programs to access this site.
The App Store Resource Center
This site provides help and advice on how to distribute your application on the
App Store, including preparing your app for submission, understanding the App
Store approval process, and learning how to manage your apps on the App Store.
You’ll need to be both a registered iPhone developer and enrolled in the iPhone
Developer Standard Program to access this site.
iTunes Connect
This site provides you with the tools to manage your applications on the iTunes
App Store and your contracts with Apple. You’ll need to be both a registered
iPhone developer and enrolled in the iPhone Developer Standard Program to access
this site.
Your iPhone Developer Program membership lasts for 1 year and can
be renewed starting 60 days before the expiration date of your existing
membership. If you do not renew your membership, your ability to dis-
tribute your applications will be curtailed. In addition, your developer
and distribution certificates will be revoked. Finally, any applications
you have on the iTunes App Store will be removed.
You have two options when enrolling in the iPhone Developer Program. Most people
will want to register for the Standard Program, which costs $99 per year. This will allow
you to create free—or, once you’ve filled out some paperwork, commercial—
applications for the iPhone and iPod touch, and distribute them either via the App Store
or via the ad hoc distribution channel where you provide both the application binary
and a provisioning certificate to the end user.
The more expensive Enterprise Program, at $299, is intended for companies with more
than 500 employees that wish to create applications for in-house distribution. While
this program allows you to distribute your applications inside your own company, it
does not allow you to publish them for sale on the App Store. If you’re thinking about
selling your applications to the public, you need the Standard Program.
An iPhone Developer University Program is also available, but this is designed specif-
ically for higher education institutes looking to introduce iPhone development into
their curricula. Unless you’re an academic at such an institute, it’s unlikely that this
program will be applicable to you.
At the time of this writing, Apple combined the iPhone SDK and Xcode
into a single download. It is possible that in future releases you may
need to install Xcode first, and then install the iPhone SDK from a sep-
arate installer.
Newer prerelease beta versions of the SDK may be available to those enrolled in the
iPhone Developer Program; however, the current stable version will be available even
if you choose not to pay to enroll in the program.
The combined download of the Xcode development tools and the iPhone SDK is around
2.5 GB in size. The combined bundle will be downloaded as a disk image file. After it
downloads, the image should automatically mount; double-click on the iPhone SDK
and Tools package file to install the SDK, as shown in Figure 2-1.
The installer will ask you to agree to the terms of the software license agreement before
prompting you to install the software. You should install it in the suggested location,
and the default installation options will include everything you need to develop appli-
cations for the iPhone or iPod touch. However, you’ll need at least 5.9 GB of free space
on your disk to install the Xcode developer tools and the iPhone SDK.
After installation, you can check that everything has gone OK by starting Xcode, which
will have been installed in the /Developer/Application folder on your machine. Project
templates should be available for the iPhone OS, as shown in Figure 2-2.
You now have everything you need to write applications and test them in the simulator.
While the simulator is very good, it’s not perfect. Code runs much faster on the simu-
lator than it does on the device. If you’re dealing with applications that have a com-
plicated UI or consume a great deal of processor power, the difference in performance
between the simulator and the device could become important. On several occasions
I’ve had to go back and rewrite my code and refactor the way in which my UI functions;
when I tested my application on the simulator it worked fine, but on real hardware it
just ran too slowly. You can also allocate much more memory in the simulator than is
available on the real hardware.
Additionally, some frameworks are available to you in the simulator—notably the
NSPredicate and NSXMLDocument classes—that just don’t exist on the device. Code that
uses these missing classes will compile and run on the simulator, but not on the device.
As well as regularly building your application in iPhone Simulator, it’s therefore a good
idea to do regular device builds. If you accidentally use one of these “missing” classes,
it will show up as a link error at compile time for such a build. After all, you don’t want
to get too far down the road of developing your application only to discover (hours, or
While I’ve seen some complaints that the simulator can sometimes be slightly off on
pixel alignment of UIKit elements, I’ve not yet come across this myself. However, when
using lower-level graphics libraries, such as OpenGL ES, the renderer used on the
iPhone and iPod touch is slightly different from the one used in the simulator, so when
a scene is displayed on the simulator it may not be identical to the actual device at the
pixel level.
Additionally, the simulator has some built-in limitations. For instance, if your appli-
cation’s UI is designed to respond to touch events with more than two fingers, you
can’t test it in the simulator.
Furthermore, you will not have access to the accelerometer, GPS, Bluetooth, or digital
compass when running your application in the simulator. If your application relies on
these hardware features, you have no choice but to test it on your device.
Figure 2-3. The workflow for creating certificates and mobile provisioning profiles
So, if you have enrolled in either the Standard or Enterprise iPhone Developer Program,
now is the time to generate the appropriate certificates and provisioning profiles so that
you will be able to deploy the test application from the next chapter onto your device.
Figure 2-4. The Certificates tab of the Keychain Access application’s Preferences pane
If you don’t see the Download option appear after you click Approve,
click the Development tab link to refresh the page, and it should appear.
Once you do this, you need to download your personal certificate and the WWDR
Intermediate certificate and install them in your Mac OS X keychain.
Still in the Development tab, click the Download button to download your personal
certificate. Next, right-click on the link to the WWDR Intermediate certificate and save
the linked file to disk.
Once both of these certificates have downloaded to your local machine, you need to
install them in your Mac OS X keychain. Double-click on the certificate files to install
them into your keychain. This will activate the Keychain Access application and ask
you to confirm that you want to add the certificates to your Mac OS X keychain.
You can check that the two certificates have been correctly installed in your keychain
by clicking on the Certificates category in the Keychain Access application. You should
see both your own developer certificate and Apple’s WWDR certificate in the login
keychain, as shown in Figure 2-6.
Figure 2-6. The Keychain Access application showing the newly installed certificates necessary for
Xcode to sign your binaries and deploy them onto your iPhone
Creating an App ID
To install your application onto your iPhone or iPod touch, you will need to create an
App ID. This is a unique identifier that the iPhone uses to grant your application access
to its section of the keychain, limiting the application’s access to usernames, passwords,
and certificates used by other applications.
The App ID is also used as part of the mobile provisioning profile. The mobile provi-
sioning profile is different from the certificate you generated earlier. Certificates stay in
the keychain on your Mac and are used by Xcode to digitally sign the iPhone application
binaries. The mobile provisioning profile you’re about to generate is tied to one or more
devices and is transferred by Xcode onto your iPhone or iPod touch. This allows the
applications you create to run on that device.
Go to the App IDs section of the iPhone Developer Program Portal, select the Manage
tab, and click on New App ID. Enter a name for your App ID; this should be a human-
readable name used to refer to this particular App ID. It’s entirely arbitrary what you
use as the name for the App ID. Since this is your first App ID, for the Bundle Seed ID
select Generate New.
Finally, enter a Bundle Identifier. This must be unique, and most developers use a
reversed version of their domain name so that this is the case. For instance, my domain
name is babilim.co.uk, so I entered uk.co.babilim.* as my Bundle Identifier.
Click Submit. The portal will now generate a new 10-character Bundle Seed ID and
prepend it to the Bundle Identifier you provided. This is your App ID.
You need to make a note of your Bundle Identifier as you’ll need to supply it to Xcode,
as described near the end of Chapter 3, to allow you to deploy the application you are
developing onto your iPhone or iPod touch.
*
* *
L'opera musicale drammatica cominciò in Germania più tardi che in
Italia e fu piuttosto frutto dell'imitazione straniera che dell'iniziativa
nazionale. Le produzioni drammatiche precedenti al Seicento si
limitavano ai Misteri e alle Moralità, alle feste carnevalesche, alle
farse di Hans Sachs ed altri poeti popolari ed a spettacoli e balletti
dati con grande sfarzo alle diverse corti dei principi di Germania.
L'opera fiorentina ed il nuovo stile rappresentativo trovarono però
imitatori molto prima che in Francia. Già nel 1627 Enrico Schütz, il
grande musicista luterano antecessore di Bach, aveva composta la
musica della Dafne di Rinuccini, tradotta da Opitz. Questo dramma
per musica fu dato a Torgau il 10 aprile 1627 in occasione delle
nozze del Landgravio di Essen con Luisa Eleonora di Sassonia.
Quantunque la musica ne sia perduta, è da ritenersi secondo le
notizie conservateci, che fosse scritta ad imitazione di quella di Peri.
E sembra pure che Schütz abbia musicato l'Orfeo di Rinuccini. Invece
ci è restata la musica di un Singspiel Seelewig (1644) di Teofilo
Staden, una specie di allegoria simile alla Rappresentazione di anima
e corpo di Emilio Cavalieri, un'opera affatto lontana dalle tendenze
della Camerata fiorentina e solo d'interesse storico.
Ma il nuovo genere non seppe attecchire, sia perchè i tempi erano
difficili e la Germania era tormentata dalla tremenda guerra dei
trent'anni, sia che mancassero gl'ingegni musicali che si volessero
applicare al nuovo genere. C'era poi un altro motivo che rendeva
difficile lo svilupparsi dell'opera nazionale. La lingua italiana era
allora di moda nelle infinite corti di Germania come lo divenne poi la
francese. Il pubblico stava in disparte e non prendeva alcun
interesse alle cose artistiche; i teatri rimasero fino alla metà del
secolo scorso con poche eccezioni riservati alla corte, ai cortigiani ed
agli invitati. Era dunque naturale che i principi si rivolgessero all'Italia
e chiamassero alle loro corti artisti italiani. Ognuna di queste aveva
un poeta di corte che doveva montare sul suo Pegaso in ogni
occasione voluta da circostanze esteriori. (Zeno e Metastasio a
Vienna, Mauro ad Hannover, Pallavicino a Dresda, Terzago a Monaco,
ecc.). I direttori erano italiani (Lotti, Caldara, Steffani, Porpora,
Iomelli, Bononcini, ecc.), italiani i cantanti (Bordoni, Cuzzoni, Lotti,
Durastanti, Senesino, Farinelli, Carestini, ecc.), italiani persino i
pittori, decoratori ed architetti. Soltanto i suonatori erano in parte
tedeschi e francesi.
Fra le corti di Germania, che videro fiorire l'opera italiana sono
specialmente da nominarsi Vienna, Dresda, Berlino e Monaco. La
corte di Vienna s'era sempre distinta quale protettrice della musica
ed ormai nel 1642 vi si eseguì l'Egisto di Cavalli. Gli imperatori
Leopoldo I, Giuseppe I e Carlo VI, buoni musicisti, preferivano la
musica italiana e cercarono con ogni modo di attirare alle loro corti i
migliori artisti italiani. Caldara e Conti assieme allo stiriano Giovanni
Fux segnano l'epoca del maggior fiore dell'opera a Vienna. Fux
(1660-1741) è tuttora noto per il suo celebre trattato Gradus ad
Parnassum (1725) e per musiche da chiesa più che per le sue opere
teatrali, nelle quali imitò gli italiani. Quasi tutti poi i più celebri
compositori italiani dell'epoca, cominciando da Cavalli, Cesti fino a
Porpora e Salieri andarono a Vienna e scrissero per quel teatro di
corte.
Non inferiore a Vienna nel culto dell'opera italiana fu Dresda. Anche
in questa città v'era un'intiera colonia artistica d'italiani, che
dominava esclusivamente il teatro. L'opera italiana vi fu inaugurata
formalmente nel 1662 col Paride di Giovanni Bontempi, scolaro di
Mazzocchi e collega di Schütz. Suo successore fu pure un italiano,
Carlo Pallavicini, buon compositore. Salito al trono Federico Augusto
I (1694), vero mecenate delle arti, cominciò una nuova era di lusso e
splendore e Dresda mai vide maggior numero di celebri artisti nelle
sue mura, fra i quali Lotti, Vittoria Tesi, il Senesino, e sopra tutti
Giovanni Adolfo Hasse e sua moglie, la famosa cantatrice Faustina
Bordoni.
Quantunque Hasse abbia avuto i natali in Germania (Bergedorf,
1699) egli appartiene interamente alla scuola napoletana ed è
compositore italiano. Da principio cantante ad Amburgo e Brunswick,
venne poi a Napoli (1724), dove si perfezionò nella composizione alla
scuola di Porpora e quindi di Alessandro Scarlatti, che lo prese ad
amare. Una sua opera, Sesostrate (1726), destò unanime applauso
ed egli già nel 1727 fu nominato direttore al Conservatorio degli
incurabili a Venezia, dove conobbe e sposò Faustina. La fama delle
sue opere oltrepassò ben presto le Alpi e pochi anni dopo venne
chiamato a Dresda (1731), dove con piccoli intervalli di tempo, fra i
quali un breve soggiorno a Londra, passò la maggior parte della sua
vita. Negli ultimi anni si recò a Venezia, dove morì nel 1783.
Hasse fu compositore fecondissimo. Dotato di grande fantasia e di
ricchezza melodica, egli dominava perfettamente la forma ed era
sommo nel trattare la voce. Ma egli non si eleva sopra i migliori
autori italiani dell'epoca, seguendo anch'egli la pratica che al bel
canto sacrificava la verità drammatica. Egli non fu e non volle essere
un riformatore ma seguì l'andazzo del tempo. Egli non copia alcuno
degli italiani ma imita tutti, togliendone da tutti il meglio, per cui egli
non è originale ma piuttosto la personificazione dello stile
drammatico, diremmo quasi astratto, italiano del secolo XVIII. Hasse
visse onorato e meritò tanto pel suo ingegno che per il suo carattere
integro il nome di Caro Sassone, che in Italia gli si diede. Colla
partenza di Hasse da Dresda (1756) e dopo la morte di Augusto III,
l'opera italiana a Dresda decadde rapidamente, durando però al
meno sporadicamente fino al 1842 (Morlacchi).
In Berlino troviamo cantanti italiani (Pasquino Grassi e Giovanni
Alberto Maglio) già nel 1656. La prima opera si diede nel 1700 e fu
la festa dell'imeneo di Attilio Ariosti, alla quale negli anni posteriori
fecero seguito delle altre finchè nel 1742 venne aperto da Federico
II il nuovo teatro con Cesare e Cleopatra di Graun. Federico il grande
era musicista appassionato e buon suonatore di flauto. Egli
prediligeva la musica italiana e non voleva saperne di cantanti
tedeschi. «Piuttosto sentir un'aria cantata da un cavallo, che una
tedesca come prima donna», soleva egli dire.
Il miglior compositore dell'epoca fu Carlo Enrico Graun (1701-1759),
che dominò colle sue opere il repertorio fino alla sua morte. Graun
appartiene pure alla scuola italiana. Scrisse 36 opere e molta musica
da chiesa, fra cui l'oratorio la Morte di Gesù, che ancor oggi si
eseguisce, opera priva di grandezza e religiosità e scritta nello stile
teatrale. Graun fu scrittore melodioso e facile, ma non ebbe nè
originalità nè potenza drammatica.
Grande influenza sulle cose musicali ebbe pure alla corte di Federico
il suo maestro di flauto Giovanni Quanz, che fu in Italia alla scuola di
Gasperini e scrisse un'infinità di composizioni per flauto ad uso del
re. Degni di menzione sono pure Francesco Benda, boemo (1709-
1786), celebre violinista, fondatore della scuola germanica, il
creatore del melodramma (declamazione con accompagnamento di
musica), e la celebre cantatrice Gertrude Elisabetta Mara per la quale
Federico ebbe a ricredersi degli artisti tedeschi. Coll'avanzarsi dell'età
venne a cessare l'interesse di Federico per l'opera, che priva del suo
più potente appoggio rapidamente decadde.
A Monaco gli Italiani erano diventati già per tempo padroni del
campo. La corte di Alberto V aveva veduto commedie italiane (1568)
per le quali aveva scritto madrigali Orlando di Lasso che in una
rappresentazione aveva egli stesso rappresentato la parte di nobile
veneziano (Pantalone dei Bisognosi). Il primo vero dramma per
musica fu la Ninfa ritrosa (1654) di autore sconosciuto. Fra tutti i
maestri di quel tempo si incontra un sol nome tedesco, Gaspare Kerl,
scolaro di Carissimi e celebre organista. Egli scrisse pure opere
teatrali andate perdute. A Kerl successero Ercole Bernabei, Giovanni
Bernabei, Agostino Steffani, Albinoni, Porta, Bernasconi. L'opera
italiana cessò nel 1787.
La patria dell'opera tedesca nazionale fu Amburgo, la libera città
anseatica, dove la musica era sempre stata in onore e dove
accorrevano gli artisti, sicuri di trovare un pubblico intelligente ed
appassionato per l'arte. Quantunque l'opera italiana fosse ben presto
giunta in Amburgo e vi avesse destato grande interesse e plauso,
pure l'elemento nazionale si fece vivo di buon'ora e molti furono i
tentativi di imitazione con tendenze nazionali e sostituzione della
lingua tedesca all'italiana. La prima opera tedesca che si diede ad
Amburgo fu Adamo ed Eva, musicata da Giovanni Theile (2 gennaio
1678). Dapprincipio essa non fu che una copia dell'italiana, ed i
soggetti si toglievano dalla mitologia, dalla storia antica e dalle
leggende sacre o dalla Bibbia. Ma il pubblico prendeva poco
interesse a quelle rappresentazioni eroiche, nelle quali esso non
trovava l'impronta nazionale ed i soggetti gli erano del tutto estranei
e punto simpatici. Ed allora nacque la reazione, dapprincipio
modesta, introducendovi l'elemento nazionale e comico e riducendo
il tutto ad una parodia di cattivo gusto. Poi l'elemento nazionale
prende il sopravento ed ai soggetti eroici e sacri si sostituiscono
azioni tolte dalla vita contemporanea, che univano il tragico al
comico, il sublime al triviale. Per sfortuna poi mai epoca fu sì povera
di buoni poeti ed i musicisti dovevano contentarsi di mettere in
musica versi che peggiori non ponno pensarsi, azioni che sono
un'ibrida congiunzioni di sciocchezze, sfacciataggini e trivialità, il
tutto condito da motti salaci in una lingua barbara ed un gergo da
piazza. La meschinità di tali produzioni drammatiche si cercava
nascondere sotto lo sfarzo delle scene, dei vestiari e dei balletti, per i
quali si spendevano somme favolose, e si cercava cancellare
l'impressione penosa d'una scena tragica con una comica della
specie più scurrile, come nell'opera di Dedekind Gesù morente, dove
Satana raccoglie in un canestro le budella di Giuda e col cestello in
mano canta un'aria.
Molto migliori dei meschini e prosaici poeti di quell'epoca furono i
maestri che posero in musica i loro tristi parti. Fra questi merita
speciale menzione Giovanni Kusser (1657-1727), musicista di
talento, il quale influì sulla nuova opera tanto colle sue opere che
colle sue cognizioni pratiche e che pel primo liberò la scena da tutta
la marmaglia di cantanti e cantatrici, tolti dal più basso volgo, che
nulla sapevano di musica e vi sostituì buoni elementi.
Ma quegli che per il suo grande ingegno, se a questo avesse unito
serietà di propositi e veri criteri artistici, sarebbe stato chiamato ad
ispirare nuova vita all'opera tedesca e metterla sul vero cammino, fu
Reinhard Keiser (1674-1739). Dotato d'inesauribile vena melodica e
vivissima fantasia egli era nato per la musica drammatica e per la
scena. Le sue numerose opere si distinguono per ricchezza e facilità
di melodia, per varietà di forma e per verità d'espressione ed egli si
innalza qualche volta a grandi altezze in scene eminentemente
drammatiche come nell'Ottavia. Le forme che usa sono piccole e
simili alla canzone popolare, ma caratteristiche e sempre adatte alle
parole. Se egli non fu capace di impedire il rapido decadimento della
giovine opera, si fu perchè gli mancava la fermezza del carattere e
seguiva l'andazzo del tempo, poco curandosi degli alti ideali, pur che
la sorte gli arridesse pel momento ed egli potesse menare vita
brillante e spensierata. Eppure ad onta dei suoi molti difetti, la sua
musica ancor oggi ha un fare sì spontaneo e naturale, è sì fresca e
melodica che bisogna meravigliarsi come in un'epoca di tali
aberrazioni del gusto potessero sbocciare fiori sì gentili.
Altra figura interessante del tempo fu Giovanni Mattheson (1681-
1764), un miscuglio d'umorista e pedante, cantante, musicista e
scrittore. Le composizioni di Mattheson sono intieramente
dimenticate, giacchè esse sono scritte nel gusto dei loro tempi e
mancano di vera ispirazione, ma non lo sono molti dei suoi infiniti
scritti d'arte e di polemica musicale, nei quali si palesa lo spirito
battagliero, ardito e mordace dello scrittore ed in mezzo a molto
ciarpame ed a frasi antiquate ed ampollose sono nascosti nuovi
pensieri ed è messa la base dell'estetica musicale moderna. (Il
perfetto direttore (1739), il patriota musicista, la porta d'onore, la
critica musicale).
L'ultimo musicista della prima epoca dell'opera d'Amburgo, dopo il
quale questa andò rapidamente decadendo, fu Giorgio Filippo
Telemann (1681-1767), artista strano, che d'ogni stile s'appropriò
qualche cosa, ma che per la manìa di essere originale ad ogni costo
cadde in mille ricercatezze e puerilità artistiche. La sua fecondità fu
prodigiosa; scrisse oltre circa 40 opere e 600 ouvertures, 44
passioni, 12 annate di musica da chiesa ed un'infinità d'altre
composizioni.
Prima di chiudere questo periodo ci resta a rammentare Händel, che
nel 1703 a 19 anni si recò ad Amburgo onde arricchire le sue
cognizioni e studiarvi l'opera. Quantunque egli abbia scritto qualche
opera per Amburgo (Almira, Nerone) e vi abbia fatto parlare di sè,
pure egli non esercitò alcuna influenza sul suo indirizzo, inquantochè
si tenne piuttosto in disparte come osservatore e pure profittando di
quello che egli ad onta della falsa strada per cui si era messa l'opera,
da questa potea apprendere, non era ancor giunto a quel grado di
maturità artistica, che per ciò era necessario. Nel 1740 arriva ad
Amburgo una compagnia d'opera italiana coll'impresario Angelo
Mingotti e l'opera nazionale tedesca, che negli ultimi anni aveva
menato un'esistenza stentata, venne a finire.
In Inghilterra la musica drammatica fu quasi sempre senza carattere
nazionale. Quantunque non sia giustificata l'opinione generalmente
diffusa della mancanza di talento musicale degli Inglesi, non è da
negarsi, che la musica in Inghilterra fu sempre influenzata dagli
stranieri, che attirati dall'idea di gloria e dalla speranza di ricchi
guadagni vi trapiantarono la musica dei loro paesi. Le prime notizie
che ci sono conservate sulla musica in Inghilterra arrivano al 600
dopo Cristo, quando papa Vitaliano mandò in Gallia e Britannia
Giovanni e Teodoro ad insegnare il canto gregoriano che in poco
tempo raggiunse grande diffusione. Dopo un lungo silenzio la storia
fa menzione di Giov. Dunstaple del quale già parlammo ed a lui
seguono molti altri musicisti pratici e teoretici, che ebbero molta
parte allo sviluppo dell'armonia e contrappunto. Verso la fine del
secolo XVI poi troviamo in Inghilterra molti musicisti, che si
occuparono specialmente del madrigale, raggiungendo in questo
genere le migliori opere degli italiani contemporanei. I più noti fra
questi sono William Bird ( † 1623), Tommaso Morley (1557-1604),
John Bull (1563-1628) e Orlando Gibbons (1583-1625). Molti
madrigali di quell'epoca sono stati ultimamente pubblicati e eseguiti
con plauso per la leggiadria dello stile, le bizzarrie ritmiche, gli
scherzi armonici e la freschezza di melodia.
Quel tempo vide pure il fiore della musica istrumentale che la regina
vergine Elisabetta preferiva e molti furono i suonatori specialmente
di virginale (specie di spinetta) che ebbero grande fama anche in
altri paesi. L'importanza di questo ramo della musica inglese è assai
grande per la storia della musica istrumentale e lo sviluppo delle sue
forme. I principali rappresentanti ne sono Hugh Aston ed i nominati
Bird e Bull. Noi troviamo nelle loro opere, che si pubblicarono negli
ultimi anni, un'assoluta indipendenza dallo stile corale, una tecnica
assai perfezionata nella mano sinistra, armonia quasi moderna e
nuove forme come per es. la variazione.
Il dramma musicale venne all'Inghilterra dall'Italia e vi fu portato da
Tommaso Lupo, Angelo Notari ed Alfonso Ferrabosco. Bisogna però
rammentare che Roberto Jones pubblicava ormai nel 1601 due libri
di songs and ayres (canti ad 1-4 voci con e senza istrumenti) scritti
nello stile recitativo delle Nuove musiche di Caccini e che qualche
cosa di simile all'opera erano le cosidette Masques con cori, danze
ed in genere musica istrumentale.
Delle prime opere di maestri inglesi (Lawes, Colman, Lock, ecc.)
sono conservati soltanto i titoli. Nel 1673 venne Cambert in
Inghilterra e vi introdusse la musica francese, che trovò tosto molti
fautori fra i quali il re Carlo II.
In quel tempo (1658) nasceva a Londra Enrico Purcell, il maggior
genio musicale che l'Inghilterra mai ebbe. Purcell ha molti punti di
somiglianza con Mozart. I suoi successi datano ormai dal suo
diciottesimo anno e le sue opere giovanili (p. es. Didone ed Enea)
mostrano maturità di studi, sicurezza di stile e di forma. Egli scrisse
una quantità di musica per azioni teatrali, da chiesa ed istrumentali,
tutte ricche di facile melodia, di ampiezza di stile e magistrale
fattura. Il maggior difetto della sua musica è quello di essere troppo
esangue e di restare quasi sempre allo stato di schizzo per quanto
geniale. Egli si formò alla scuola degli Italiani senza però rinunciare
alla sua personalità spiccata ma altresì senza raggiungerli. Egli
prelude però ormai ad Händel specialmente colla sua maniera di
innestare il coro all'azione e di concepire il quadro musicale.
Purcell non trovò chi raccogliesse il suo retaggio. Morto a 37 anni,
venne ben presto dimenticato dal pubblico che preferiva i piccanti
ritmi delle canzoni francesi alla verità drammatica delle sue opere ed
alla grandiosità dei suoi cori.
Dopo la morte di Cambert (1677) sono di nuovo gli italiani che
predominano e contendono la palma ad Händel, mentre gli ultimi
tentativi di un'opera nazionale (Beggar's Opéra di Gay 1727) cadono
sotto il livello dei più meschini prodotti.
LETTERATURA
LETTERATURA