Inter-App Communication
2015-09-09 07:33
295 查看
Appscommunicateonlyindirectlywithotherappsonadevice.YoucanuseAirDroptosharefilesanddatawithotherapps.YoucanalsodefineacustomURLschemesothatappscansendinformationtoyourappusingURLs.
Note:Youcanalsosendfilesbetweenappsusinga
oradocumentpicker.Forinformationaboutaddingsupportforadocumentinteractioncontroller,seeDocument
InteractionProgrammingTopicsforiOS.Forinformationaboutusingadocumentpickertoopenfiles,seeDocument
PickerProgrammingGuide.
AirDropletsyousharephotos,documents,URLs,andothertypesofdatawithnearbydevices.AirDroptakesadvantageofpeer-to-peernetworkingtofindnearbydevicesandconnecttothem.
TosendfilesanddatausingAirDrop,usea
todisplayanactivitysheetfromyouruserinterfaceusing.Whencreatingthisviewcontroller,youspecifythedataobjectsthatyouwanttoshare.Theviewcontrollerdisplaysonlythoseactivitiesthatsupportthespecifieddata.ForAirDrop,youcanspecify
images,strings,URLs,andseveralothertypesofdata.Youcanalsopasscustomobjectsthatadoptthe
Todisplayanactivityviewcontroller,youcanusecodesimilartothatshowninListing6-1.Theactivity
viewcontrollerautomaticallyusesthetypeofthespecifiedobjecttodeterminewhatactivitiestodisplayintheactivitysheet.YoudonothavetospecifytheAirDropactivityexplicitly.However,youcanpreventthesheetfromdisplayingspecifictypes
usingtheviewcontroller’s
WhendisplayinganactivityviewcontrolleroniPad,youmustuseapopover.
Listing6-1DisplayinganactivitysheetoniPhone
Formoreinformationaboutusingtheactivityviewcontroller,seeUIActivityViewController
ClassReference.Foracompletelistofactivitiesandthedatatypestheysupport,seeUIActivity
ClassReference.
ToreceivefilessenttoyourappusingAirDrop,dothefollowing:
InXcode,declaresupportforthedocumenttypesyourappiscapableofopening.
Inyourappdelegate,implementthe
Usethatmethodtoreceivethedatathatwassentbytheotherapp.
Bepreparedtolookforfilesinyourapp’s
movethemoutofthatdirectoryasneeded.
TheInfotabofyourXcodeprojectcontainsaDocumentTypessectionforspecifyingthedocumenttypesyourappsupports.Ataminimum,youmustspecifyanameforyourdocumenttypeandoneormoreUTIsthat
representthedatatype.Forexample,todeclaresupportforPNGfiles,youwouldinclude
UTIstodetermineifyourappiseligibletoopenagivendocument.
Aftertransferringaneligibledocumenttoyourapp’scontainer,iOSlaunchesyourapp(ifneeded)andcallsthe
ofitsappdelegate.Ifyourappisintheforeground,youshouldusethismethodtoopenthefileanddisplayittotheuser.Ifyourappisinthebackground,youmightdecideonlytonotethatthefileistheresothatyoucanopenitlater.Becausefiles
transferredviaAirDropareencryptedusingdataprotection,youcannotopenfilesunlessthedeviceiscurrentlyunlocked.
FilestransferredtoyourappusingAirDropareplacedinyourapp’s
Yourapphaspermissiontoreadanddeletefilesinthisdirectorybutitdoesnothavepermissiontowritetofiles.Ifyouplantomodifythefile,youmustmoveitoutofthe
beforedoingso.Itisrecommendedthatyoudeletefilesfromthe
Formoreinformationaboutsupportingdocumenttypesinyourapp,seeDocument-Based
AppProgrammingGuideforiOS.
AURLschemeletsyoucommunicatewithotherappsthroughaprotocolthatyoudefine.Tocommunicatewithanappthatimplementssuchascheme,youmustcreateanappropriatelyformattedURLandaskthesystem
toopenit.Toimplementsupportforacustomscheme,youmustdeclaresupportfortheschemeandhandleincomingURLsthatusethescheme.
Note:Appleprovidesbuilt-insupportforthe
and
URLstargetedattheMaps,YouTube,andiPodapps.Thehandlersfortheseschemesarefixedandcannotbechanged.IfyourURLtypeincludesaschemethatisidenticaltoonedefinedbyApple,theApple-providedappislaunchedinsteadofyourapp.Forinformation
abouttheschemessupportedbyapple,seeApple
URLSchemeReference.
WhenyouwanttosenddatatoanappthatimplementsacustomURLscheme,createanappropriatelyformattedURLandcallthe
oftheappobject.The
thenewapp.
Thefollowingcodefragmentillustrateshowoneappcanrequesttheservicesofanotherapp(“todolist”inthisexampleisahypotheticalcustomschemeregisteredbyanapp):
IfyourappdefinesacustomURLscheme,itshouldimplementahandlerforthatschemeasdescribedinImplementing
CustomURLSchemes.Formoreinformationaboutthesystem-supportedURLschemes,includinginformationabouthowtoformattheURLs,seeApple
URLSchemeReference.
IfyourappcanreceivespeciallyformattedURLs,youshouldregisterthecorrespondingURLschemeswiththesystem.AppsoftenusecustomURLschemestovendservicestootherapps.Forexample,theMapsapp
supportsURLsfordisplayingspecificmaplocations.
ToregisteraURLtypeforyourapp,includethe
The
6-1describesthekeysandvaluestoincludeineachdictionary.
Table6-1Keysandvaluesofthe
Note:Ifmorethanonethird-partyappregisterstohandlethesameURLscheme,thereiscurrentlynoprocessfordeterminingwhichappwillbegiventhatscheme.
AnappthathasitsowncustomURLschememustbeabletohandleURLspassedtoit.AllURLsarepassedtoyourapp
delegate,eitheratlaunchtimeorwhileyourappisrunningorinthebackground.TohandleincomingURLs,yourdelegateshouldimplementthefollowingmethods:
Usethe
toretrieveinformationabouttheURLanddecidewhetheryouwanttoopenit.Ifeithermethodreturns
yourapp’sURLhandlingcodeisnotcalled.
Usethe
toopenthefile.
IfyourappisnotrunningwhenaURLrequestarrives,itislaunchedandmovedtotheforegroundsothatitcanopentheURL.Theimplementationofyour
shouldretrievetheURLfromitsoptionsdictionaryanddeterminewhethertheappcanopenit.Ifitcan,return
letyour
methodhandletheactualopeningoftheURL.(Ifyouimplementbothmethods,bothmustreturn
theURLcanbeopened.)Figure6-1showsthemodifiedlaunchsequenceforanappthatisaskedtoopenaURL.
Figure6-1LaunchinganapptoopenaURL
IfyourappisrunningbutisinthebackgroundorsuspendedwhenaURLrequestarrives,itismovedtotheforegroundtoopentheURL.Shortlythereafter,thesystemcallsthedelegate’s
checktheURLandopenit.Figure6-2showsthemodifiedprocessformovinganapptotheforegroundtoopenaURL.
Figure6-2Wakingabackgroundapptoopen
aURL
Note:AppsthatsupportcustomURLschemescanspecifydifferentlaunchimagestobedisplayedwhenlaunchingtheapptohandleaURL.Formoreinformationabouthowtospecify
theselaunchimages,seeDisplaying
aCustomLaunchImageWhenaURLisOpened.
AllURLsarepassedtoyourappinan
ItisuptoyoutodefinetheformatoftheURL,butthe
conventions.Specifically,theclassincludesmethodsthatreturnthevariouspartsofaURLasdefinedbyRFC1808,includingtheuser,password,query,fragment,andparameterstrings.The“protocol”foryourcustomschemecanusetheseURLpartsforconveying
variouskindsofinformation.
Intheimplementationof
inListing6-2,thepassed-inURLobjectconveysapp-specificinformationinitsqueryandfragmentparts.Thedelegateextractsthisinformation—inthis
case,thenameofato-dotaskandthedatethetaskisdue—andwithitcreatesamodelobjectoftheapp.ThisexampleassumesthattheuserisusingaGregoriancalendar.Ifyourappsupportsnon-Gregoriancalendars,youneedtodesignyourURLschemeaccordingly
andbepreparedtohandlethoseothercalendartypesinyourcode.
Listing6-2HandlingaURLrequestbasedonacustomscheme
BesuretovalidatetheinputyougetfromURLspassedtoyourapp;seeValidating
InputandInterprocessCommunicationinSecure
CodingGuidetofindouthowtoavoidproblemsrelatedtoURLhandling.TolearnaboutURLschemesdefinedbyApple,seeApple
URLSchemeReference.
AppsthatsupportcustomURLschemescanprovideacustomlaunchimageforeachscheme.WhenthesystemlaunchesyourapptohandleaURLandnorelevantsnapshotisavailable,itdisplaysthelaunchimageyou
specify.Tospecifyalaunchimage,provideaPNGimagewhosenameusesthefollowingnamingconventions:
<basename>
Inthisnamingconvention,basenamerepresentsthebaseimagenamespecifiedbythe
inyourapp’s
The<url_scheme>portionofthenameisyourURLschemename.Tospecifyagenericlaunchimageforthe
animagefilewiththename
Ifyourappalsosupportsstandardresolutiondisplays,youwouldalsoprovidea
Forinformationabouttheothermodifiersyoucanincludeinlaunchimagenames,seethedescriptionofthe
keyinInformation
PropertyListKeyReference.
Note:Youcanalsosendfilesbetweenappsusinga
objectUIDocumentInteractionController
oradocumentpicker.Forinformationaboutaddingsupportforadocumentinteractioncontroller,seeDocument
InteractionProgrammingTopicsforiOS.Forinformationaboutusingadocumentpickertoopenfiles,seeDocument
PickerProgrammingGuide.
SupportingAirDrop
AirDropletsyousharephotos,documents,URLs,andothertypesofdatawithnearbydevices.AirDroptakesadvantageofpeer-to-peernetworkingtofindnearbydevicesandconnecttothem.
SendingFilesandDatatoAnotherApp
TosendfilesanddatausingAirDrop,useaobjectUIActivityViewController
todisplayanactivitysheetfromyouruserinterfaceusing.Whencreatingthisviewcontroller,youspecifythedataobjectsthatyouwanttoshare.Theviewcontrollerdisplaysonlythoseactivitiesthatsupportthespecifieddata.ForAirDrop,youcanspecify
images,strings,URLs,andseveralothertypesofdata.Youcanalsopasscustomobjectsthatadoptthe
protocol.UIActivityItemSource
Todisplayanactivityviewcontroller,youcanusecodesimilartothatshowninListing6-1.Theactivity
viewcontrollerautomaticallyusesthetypeofthespecifiedobjecttodeterminewhatactivitiestodisplayintheactivitysheet.YoudonothavetospecifytheAirDropactivityexplicitly.However,youcanpreventthesheetfromdisplayingspecifictypes
usingtheviewcontroller’s
property.excludedActivityTypes
WhendisplayinganactivityviewcontrolleroniPad,youmustuseapopover.
Listing6-1DisplayinganactivitysheetoniPhone
-(void)displayActivityControllerWithDataObject:(id)obj{ |
UIActivityViewController*vc=[[UIActivityViewControlleralloc] |
initWithActivityItems:@[obj]applicationActivities:nil]; |
[selfpresentViewController:vcanimated:YEScompletion:nil]; |
} |
ClassReference.Foracompletelistofactivitiesandthedatatypestheysupport,seeUIActivity
ClassReference.
ReceivingFilesandDataSenttoYourApp
ToreceivefilessenttoyourappusingAirDrop,dothefollowing:InXcode,declaresupportforthedocumenttypesyourappiscapableofopening.
Inyourappdelegate,implementthe
method.application:openURL:sourceApplication:annotation:
Usethatmethodtoreceivethedatathatwassentbytheotherapp.
Bepreparedtolookforfilesinyourapp’s
Documents/Inboxdirectoryand
movethemoutofthatdirectoryasneeded.
TheInfotabofyourXcodeprojectcontainsaDocumentTypessectionforspecifyingthedocumenttypesyourappsupports.Ataminimum,youmustspecifyanameforyourdocumenttypeandoneormoreUTIsthat
representthedatatype.Forexample,todeclaresupportforPNGfiles,youwouldinclude
public.pngastheUTIstring.iOSusesthespecified
UTIstodetermineifyourappiseligibletoopenagivendocument.
Aftertransferringaneligibledocumenttoyourapp’scontainer,iOSlaunchesyourapp(ifneeded)andcallsthe
application:openURL:sourceApplication:annotation:method
ofitsappdelegate.Ifyourappisintheforeground,youshouldusethismethodtoopenthefileanddisplayittotheuser.Ifyourappisinthebackground,youmightdecideonlytonotethatthefileistheresothatyoucanopenitlater.Becausefiles
transferredviaAirDropareencryptedusingdataprotection,youcannotopenfilesunlessthedeviceiscurrentlyunlocked.
FilestransferredtoyourappusingAirDropareplacedinyourapp’s
Documents/Inboxdirectory.
Yourapphaspermissiontoreadanddeletefilesinthisdirectorybutitdoesnothavepermissiontowritetofiles.Ifyouplantomodifythefile,youmustmoveitoutofthe
Inboxdirectory
beforedoingso.Itisrecommendedthatyoudeletefilesfromthe
Inboxdirectorywhenyounolongerneedthem.
Formoreinformationaboutsupportingdocumenttypesinyourapp,seeDocument-Based
AppProgrammingGuideforiOS.
UsingURLSchemestoCommunicatewithApps
AURLschemeletsyoucommunicatewithotherappsthroughaprotocolthatyoudefine.Tocommunicatewithanappthatimplementssuchascheme,youmustcreateanappropriatelyformattedURLandaskthesystemtoopenit.Toimplementsupportforacustomscheme,youmustdeclaresupportfortheschemeandhandleincomingURLsthatusethescheme.
Note:Appleprovidesbuilt-insupportforthe
http,
mailto,
tel,
and
smsURLschemesamongothers.Italsosupports
http–based
URLstargetedattheMaps,YouTube,andiPodapps.Thehandlersfortheseschemesarefixedandcannotbechanged.IfyourURLtypeincludesaschemethatisidenticaltoonedefinedbyApple,theApple-providedappislaunchedinsteadofyourapp.Forinformation
abouttheschemessupportedbyapple,seeApple
URLSchemeReference.
SendingaURLtoAnotherApp
WhenyouwanttosenddatatoanappthatimplementsacustomURLscheme,createanappropriatelyformattedURLandcallthemethodopenURL:
oftheappobject.The
openURL:methodlaunchestheappwiththeregisteredschemeandpassesyourURLtoit.Atthatpoint,controlpassesto
thenewapp.
Thefollowingcodefragmentillustrateshowoneappcanrequesttheservicesofanotherapp(“todolist”inthisexampleisahypotheticalcustomschemeregisteredbyanapp):
NSURL*myURL=[NSURLURLWithString:@"todolist://www.acme.com?Quarterly%20Report#200806231300"]; |
[[UIApplicationsharedApplication]openURL:myURL]; |
CustomURLSchemes.Formoreinformationaboutthesystem-supportedURLschemes,includinginformationabouthowtoformattheURLs,seeApple
URLSchemeReference.
ImplementingCustomURLSchemes
IfyourappcanreceivespeciallyformattedURLs,youshouldregisterthecorrespondingURLschemeswiththesystem.AppsoftenusecustomURLschemestovendservicestootherapps.Forexample,theMapsappsupportsURLsfordisplayingspecificmaplocations.
RegisteringCustomURLSchemes
ToregisteraURLtypeforyourapp,includetheCFBundleURLTypeskeyinyourapp’s
Info.plistfile.
The
CFBundleURLTypeskeycontainsanarrayofdictionaries,eachofwhichdefinesaURLschemetheappsupports.Table
6-1describesthekeysandvaluestoincludeineachdictionary.
Key | Value |
---|---|
CFBundleURLName | AstringcontainingtheabstractnameoftheURLscheme.Toensureuniqueness,itisrecommendedthatyouspecifyareverse-DNSstyleofidentifier,forexample,com.acme.myscheme. Thestringyouspecifyisalsousedasakeyinyourapp’s InfoPlist.stringsfile.Thevalueofthekeyisthehuman-readableschemename. |
CFBundleURLSchemes | AnarrayofstringscontainingtheURLschemenames—forexample,http, mailto, tel, and sms. |
HandlingURLRequests
AnappthathasitsowncustomURLschememustbeabletohandleURLspassedtoit.AllURLsarepassedtoyourappdelegate,eitheratlaunchtimeorwhileyourappisrunningorinthebackground.TohandleincomingURLs,yourdelegateshouldimplementthefollowingmethods:
Usethe
andapplication:willFinishLaunchingWithOptions:
methodsapplication:didFinishLaunchingWithOptions:
toretrieveinformationabouttheURLanddecidewhetheryouwanttoopenit.Ifeithermethodreturns
,NO
yourapp’sURLhandlingcodeisnotcalled.
Usethe
methodapplication:openURL:sourceApplication:annotation:
toopenthefile.
IfyourappisnotrunningwhenaURLrequestarrives,itislaunchedandmovedtotheforegroundsothatitcanopentheURL.Theimplementationofyour
application:willFinishLaunchingWithOptions:or
application:didFinishLaunchingWithOptions:method
shouldretrievetheURLfromitsoptionsdictionaryanddeterminewhethertheappcanopenit.Ifitcan,return
andYES
letyour
application:openURL:sourceApplication:annotation:(or
application:handleOpenURL:)
methodhandletheactualopeningoftheURL.(Ifyouimplementbothmethods,bothmustreturn
beforeYES
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
object.NSURL
ItisuptoyoutodefinetheformatoftheURL,butthe
NSURLclassconformstotheRFC1808specificationandthereforesupportsmostURLformatting
conventions.Specifically,theclassincludesmethodsthatreturnthevariouspartsofaURLasdefinedbyRFC1808,includingtheuser,password,query,fragment,andparameterstrings.The“protocol”foryourcustomschemecanusetheseURLpartsforconveying
variouskindsofinformation.
Intheimplementationof
shownapplication:openURL:sourceApplication:annotation:
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; |
} |
InputandInterprocessCommunicationinSecure
CodingGuidetofindouthowtoavoidproblemsrelatedtoURLhandling.TolearnaboutURLschemesdefinedbyApple,seeApple
URLSchemeReference.
DisplayingaCustomLaunchImageWhenaURLisOpened
AppsthatsupportcustomURLschemescanprovideacustomlaunchimageforeachscheme.WhenthesystemlaunchesyourapptohandleaURLandnorelevantsnapshotisavailable,itdisplaysthelaunchimageyouspecify.Tospecifyalaunchimage,provideaPNGimagewhosenameusesthefollowingnamingconventions:
<basename>
-<url_scheme><other_modifiers>
.png
Inthisnamingconvention,basenamerepresentsthebaseimagenamespecifiedbythe
UILaunchImageFilekey
inyourapp’s
Info.plistfile.Ifyoudonotspecifyacustombasename,usethestring
Default.
The<url_scheme>portionofthenameisyourURLschemename.Tospecifyagenericlaunchimageforthe
myappURLscheme,youwouldinclude
animagefilewiththename
Default-myapp@2x.pngintheapp’sbundle.(The@2xmodifiersignifiesthattheimageisintendedforRetinadisplays.
Ifyourappalsosupportsstandardresolutiondisplays,youwouldalsoprovidea
Default-myapp.pngimage.)
Forinformationabouttheothermodifiersyoucanincludeinlaunchimagenames,seethedescriptionofthe
UILaunchImageFilename
keyinInformation
PropertyListKeyReference.
相关文章推荐
- 两分钟彻底让你明白Android Activity生命周期(图文)!
- cocos2dx骨骼动画Armature源码剖析(一)
- cocos2dx骨骼动画Armature源码剖析(二)
- cocos2dx骨骼动画Armature源码剖析(三)
- Android Api Demos登顶之路(六十一)Content-->PickContacts
- Leetcode #42 Trapping Rain Water
- ios下App目录详解
- iOS-runtime-objc_setAssociatedObject(关联对象以及传值)
- Leetcode #202 Happy Number
- Runtime运行时机制
- cocos3.x更改layer,scene锚点
- 【Unity3D_常用模块】 事件管理器
- 加速Android Studio/Gradle构建
- Android采用ListView实现数据列表显示1-使用SimpleCursorAdapter进行数据绑定
- unity3d插件
- Unity 模型的制作规范
- Unity3D占用内存太大的解决方法
- 【Android】2015.09.08 第一行代码 Day6 Count:8
- Unity3D普通类和继承自MonoBehaviour类的区别
- android BaseAdapter