您的位置:首页 > 移动开发

Inter-App Communication

2015-09-09 07:33 295 查看
Appscommunicateonlyindirectlywithotherappsonadevice.YoucanuseAirDroptosharefilesanddatawithotherapps.YoucanalsodefineacustomURLschemesothatappscansendinformationtoyourappusingURLs.

Note:Youcanalsosendfilesbetweenappsusinga
UIDocumentInteractionController
object
oradocumentpicker.Forinformationaboutaddingsupportforadocumentinteractioncontroller,seeDocument
InteractionProgrammingTopicsforiOS.Forinformationaboutusingadocumentpickertoopenfiles,seeDocument
PickerProgrammingGuide.


SupportingAirDrop

AirDropletsyousharephotos,documents,URLs,andothertypesofdatawithnearbydevices.AirDroptakesadvantageofpeer-to-peernetworkingtofindnearbydevicesandconnecttothem.


SendingFilesandDatatoAnotherApp

TosendfilesanddatausingAirDrop,usea
UIActivityViewController
object
todisplayanactivitysheetfromyouruserinterfaceusing.Whencreatingthisviewcontroller,youspecifythedataobjectsthatyouwanttoshare.Theviewcontrollerdisplaysonlythoseactivitiesthatsupportthespecifieddata.ForAirDrop,youcanspecify
images,strings,URLs,andseveralothertypesofdata.Youcanalsopasscustomobjectsthatadoptthe
UIActivityItemSource
protocol.
Todisplayanactivityviewcontroller,youcanusecodesimilartothatshowninListing6-1.Theactivity
viewcontrollerautomaticallyusesthetypeofthespecifiedobjecttodeterminewhatactivitiestodisplayintheactivitysheet.YoudonothavetospecifytheAirDropactivityexplicitly.However,youcanpreventthesheetfromdisplayingspecifictypes
usingtheviewcontroller’s
excludedActivityTypes
property.
WhendisplayinganactivityviewcontrolleroniPad,youmustuseapopover.

Listing6-1DisplayinganactivitysheetoniPhone

-(void)displayActivityControllerWithDataObject:(id)obj{

UIActivityViewController*vc=[[UIActivityViewControlleralloc]

initWithActivityItems:@[obj]applicationActivities:nil];

[selfpresentViewController:vcanimated:YEScompletion:nil];

}

Formoreinformationaboutusingtheactivityviewcontroller,seeUIActivityViewController
ClassReference.Foracompletelistofactivitiesandthedatatypestheysupport,seeUIActivity
ClassReference.


ReceivingFilesandDataSenttoYourApp

ToreceivefilessenttoyourappusingAirDrop,dothefollowing:

InXcode,declaresupportforthedocumenttypesyourappiscapableofopening.

Inyourappdelegate,implementthe
application:openURL:sourceApplication:annotation:
method.
Usethatmethodtoreceivethedatathatwassentbytheotherapp.

Bepreparedtolookforfilesinyourapp’s
Documents/Inbox
directoryand
movethemoutofthatdirectoryasneeded.

TheInfotabofyourXcodeprojectcontainsaDocumentTypessectionforspecifyingthedocumenttypesyourappsupports.Ataminimum,youmustspecifyanameforyourdocumenttypeandoneormoreUTIsthat
representthedatatype.Forexample,todeclaresupportforPNGfiles,youwouldinclude
public.png
astheUTIstring.iOSusesthespecified
UTIstodetermineifyourappiseligibletoopenagivendocument.
Aftertransferringaneligibledocumenttoyourapp’scontainer,iOSlaunchesyourapp(ifneeded)andcallsthe
application:openURL:sourceApplication:annotation:
method
ofitsappdelegate.Ifyourappisintheforeground,youshouldusethismethodtoopenthefileanddisplayittotheuser.Ifyourappisinthebackground,youmightdecideonlytonotethatthefileistheresothatyoucanopenitlater.Becausefiles
transferredviaAirDropareencryptedusingdataprotection,youcannotopenfilesunlessthedeviceiscurrentlyunlocked.
FilestransferredtoyourappusingAirDropareplacedinyourapp’s
Documents/Inbox
directory.
Yourapphaspermissiontoreadanddeletefilesinthisdirectorybutitdoesnothavepermissiontowritetofiles.Ifyouplantomodifythefile,youmustmoveitoutofthe
Inbox
directory
beforedoingso.Itisrecommendedthatyoudeletefilesfromthe
Inbox
directorywhenyounolongerneedthem.
Formoreinformationaboutsupportingdocumenttypesinyourapp,seeDocument-Based
AppProgrammingGuideforiOS.


UsingURLSchemestoCommunicatewithApps

AURLschemeletsyoucommunicatewithotherappsthroughaprotocolthatyoudefine.Tocommunicatewithanappthatimplementssuchascheme,youmustcreateanappropriatelyformattedURLandaskthesystem
toopenit.Toimplementsupportforacustomscheme,youmustdeclaresupportfortheschemeandhandleincomingURLsthatusethescheme.

Note:Appleprovidesbuilt-insupportforthe
http
,
mailto
,
tel
,
and
sms
URLschemesamongothers.Italsosupports
http
–based
URLstargetedattheMaps,YouTube,andiPodapps.Thehandlersfortheseschemesarefixedandcannotbechanged.IfyourURLtypeincludesaschemethatisidenticaltoonedefinedbyApple,theApple-providedappislaunchedinsteadofyourapp.Forinformation
abouttheschemessupportedbyapple,seeApple
URLSchemeReference.


SendingaURLtoAnotherApp

WhenyouwanttosenddatatoanappthatimplementsacustomURLscheme,createanappropriatelyformattedURLandcallthe
openURL:
method
oftheappobject.The
openURL:
methodlaunchestheappwiththeregisteredschemeandpassesyourURLtoit.Atthatpoint,controlpassesto
thenewapp.
Thefollowingcodefragmentillustrateshowoneappcanrequesttheservicesofanotherapp(“todolist”inthisexampleisahypotheticalcustomschemeregisteredbyanapp):

NSURL*myURL=[NSURLURLWithString:@"todolist://www.acme.com?Quarterly%20Report#200806231300"];

[[UIApplicationsharedApplication]openURL:myURL];

IfyourappdefinesacustomURLscheme,itshouldimplementahandlerforthatschemeasdescribedinImplementing
CustomURLSchemes.Formoreinformationaboutthesystem-supportedURLschemes,includinginformationabouthowtoformattheURLs,seeApple
URLSchemeReference.


ImplementingCustomURLSchemes

IfyourappcanreceivespeciallyformattedURLs,youshouldregisterthecorrespondingURLschemeswiththesystem.AppsoftenusecustomURLschemestovendservicestootherapps.Forexample,theMapsapp
supportsURLsfordisplayingspecificmaplocations.


RegisteringCustomURLSchemes

ToregisteraURLtypeforyourapp,includethe
CFBundleURLTypes
keyinyourapp’s
Info.plist
file.
The
CFBundleURLTypes
keycontainsanarrayofdictionaries,eachofwhichdefinesaURLschemetheappsupports.Table
6-1describesthekeysandvaluestoincludeineachdictionary.

Table6-1Keysandvaluesofthe
CFBundleURLTypes
property

Key
Value
CFBundleURLName

AstringcontainingtheabstractnameoftheURLscheme.Toensureuniqueness,itisrecommendedthatyouspecifyareverse-DNSstyleofidentifier,forexample,
com.acme.myscheme
.

Thestringyouspecifyisalsousedasakeyinyourapp’s
InfoPlist.strings
file.Thevalueofthekeyisthehuman-readableschemename.
CFBundleURLSchemes

AnarrayofstringscontainingtheURLschemenames—forexample,
http
,
mailto
,
tel
,
and
sms
.
Note:Ifmorethanonethird-partyappregisterstohandlethesameURLscheme,thereiscurrentlynoprocessfordeterminingwhichappwillbegiventhatscheme.


HandlingURLRequests

AnappthathasitsowncustomURLschememustbeabletohandleURLspassedtoit.AllURLsarepassedtoyourapp
delegate,eitheratlaunchtimeorwhileyourappisrunningorinthebackground.TohandleincomingURLs,yourdelegateshouldimplementthefollowingmethods:

Usethe
application:willFinishLaunchingWithOptions:
and
application:didFinishLaunchingWithOptions:
methods
toretrieveinformationabouttheURLanddecidewhetheryouwanttoopenit.Ifeithermethodreturns
NO
,
yourapp’sURLhandlingcodeisnotcalled.

Usethe
application:openURL:sourceApplication:annotation:
method
toopenthefile.

IfyourappisnotrunningwhenaURLrequestarrives,itislaunchedandmovedtotheforegroundsothatitcanopentheURL.Theimplementationofyour
application:willFinishLaunchingWithOptions:
or
application:didFinishLaunchingWithOptions:
method
shouldretrievetheURLfromitsoptionsdictionaryanddeterminewhethertheappcanopenit.Ifitcan,return
YES
and
letyour
application:openURL:sourceApplication:annotation:
(or
application:handleOpenURL:
)
methodhandletheactualopeningoftheURL.(Ifyouimplementbothmethods,bothmustreturn
YES
before
theURLcanbeopened.)Figure6-1showsthemodifiedlaunchsequenceforanappthatisaskedtoopenaURL.
Figure6-1LaunchinganapptoopenaURL


IfyourappisrunningbutisinthebackgroundorsuspendedwhenaURLrequestarrives,itismovedtotheforegroundtoopentheURL.Shortlythereafter,thesystemcallsthedelegate’s
application:openURL:sourceApplication:annotation:
to
checktheURLandopenit.Figure6-2showsthemodifiedprocessformovinganapptotheforegroundtoopenaURL.
Figure6-2Wakingabackgroundapptoopen
aURL


Note:AppsthatsupportcustomURLschemescanspecifydifferentlaunchimagestobedisplayedwhenlaunchingtheapptohandleaURL.Formoreinformationabouthowtospecify
theselaunchimages,seeDisplaying
aCustomLaunchImageWhenaURLisOpened.

AllURLsarepassedtoyourappinan
NSURL
object.
ItisuptoyoutodefinetheformatoftheURL,butthe
NSURL
classconformstotheRFC1808specificationandthereforesupportsmostURLformatting
conventions.Specifically,theclassincludesmethodsthatreturnthevariouspartsofaURLasdefinedbyRFC1808,includingtheuser,password,query,fragment,andparameterstrings.The“protocol”foryourcustomschemecanusetheseURLpartsforconveying
variouskindsofinformation.
Intheimplementationof
application:openURL:sourceApplication:annotation:
shown
inListing6-2,thepassed-inURLobjectconveysapp-specificinformationinitsqueryandfragmentparts.Thedelegateextractsthisinformation—inthis
case,thenameofato-dotaskandthedatethetaskisdue—andwithitcreatesamodelobjectoftheapp.ThisexampleassumesthattheuserisusingaGregoriancalendar.Ifyourappsupportsnon-Gregoriancalendars,youneedtodesignyourURLschemeaccordingly
andbepreparedtohandlethoseothercalendartypesinyourcode.

Listing6-2HandlingaURLrequestbasedonacustomscheme

-(BOOL)application:(UIApplication*)applicationopenURL:(NSURL*)url

sourceApplication:(NSString*)sourceApplicationannotation:(id)annotation{

if([[urlscheme]isEqualToString:@"todolist"]){

ToDoItem*item=[[ToDoItemalloc]init];

NSString*taskName=[urlquery];

if(!taskName||![selfisValidTaskString:taskName]){//musthaveataskname

returnNO;

}

taskName=[taskNamestringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];


item.toDoTask=taskName;

NSString*dateString=[urlfragment];

if(!dateString||[dateStringisEqualToString:@"today"]){

item.dateDue=[NSDatedate];

}else{

if(![selfisValidDateString:dateString]){

returnNO;

}

//format:yyyymmddhhmm(24-hourclock)

NSString*curStr=[dateStringsubstringWithRange:NSMakeRange(0,4)];

NSIntegeryeardigit=[curStrintegerValue];

curStr=[dateStringsubstringWithRange:NSMakeRange(4,2)];

NSIntegermonthdigit=[curStrintegerValue];

curStr=[dateStringsubstringWithRange:NSMakeRange(6,2)];

NSIntegerdaydigit=[curStrintegerValue];

curStr=[dateStringsubstringWithRange:NSMakeRange(8,2)];

NSIntegerhourdigit=[curStrintegerValue];

curStr=[dateStringsubstringWithRange:NSMakeRange(10,2)];

NSIntegerminutedigit=[curStrintegerValue];


NSDateComponents*dateComps=[[NSDateComponentsalloc]init];

[dateCompssetYear:yeardigit];

[dateCompssetMonth:monthdigit];

[dateCompssetDay:daydigit];

[dateCompssetHour:hourdigit];

[dateCompssetMinute:minutedigit];

NSCalendar*calendar=[s[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar];

NSDate*itemDate=[calendardateFromComponents:dateComps];

if(!itemDate){

returnNO;

}

item.dateDue=itemDate;

}


[(NSMutableArray*)self.listaddObject:item];

returnYES;

}

returnNO;

}

BesuretovalidatetheinputyougetfromURLspassedtoyourapp;seeValidating
InputandInterprocessCommunicationinSecure
CodingGuidetofindouthowtoavoidproblemsrelatedtoURLhandling.TolearnaboutURLschemesdefinedbyApple,seeApple
URLSchemeReference.


DisplayingaCustomLaunchImageWhenaURLisOpened

AppsthatsupportcustomURLschemescanprovideacustomlaunchimageforeachscheme.WhenthesystemlaunchesyourapptohandleaURLandnorelevantsnapshotisavailable,itdisplaysthelaunchimageyou
specify.Tospecifyalaunchimage,provideaPNGimagewhosenameusesthefollowingnamingconventions:
<basename>
-
<url_scheme><other_modifiers>
.png

Inthisnamingconvention,basenamerepresentsthebaseimagenamespecifiedbythe
UILaunchImageFile
key
inyourapp’s
Info.plist
file.Ifyoudonotspecifyacustombasename,usethestring
Default
.
The<url_scheme>portionofthenameisyourURLschemename.Tospecifyagenericlaunchimageforthe
myapp
URLscheme,youwouldinclude
animagefilewiththename
Default-myapp@2x.png
intheapp’sbundle.(The@2xmodifiersignifiesthattheimageisintendedforRetinadisplays.
Ifyourappalsosupportsstandardresolutiondisplays,youwouldalsoprovidea
Default-myapp.png
image.)
Forinformationabouttheothermodifiersyoucanincludeinlaunchimagenames,seethedescriptionofthe
UILaunchImageFile
name
keyinInformation
PropertyListKeyReference.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: