1. 개요
Custom Scheme 형식
custom-scheme://?callback=appCalled&message=앱 호출하기
- custom-scheme : 앱의 스키마명을 의미합니다. 해당 값에 대한 설정은 다음 단계에서 진행합니다.
- ?{key}={value} : 앱을 호출할 때 전달할 파라미터입니다. &로 연결되어 계속 추가할 수 있습니다.
Android <> iOS Difference
- iOS는 host가 없다
- 안드로이드와 달리 특정 ViewController를 열수 없고 단순 앱 호출이라는 점입니다.
- 물론 구현 방식에 따라 안드로이드와 동일하게 동작하게끔 구현할 수도 있습니다.
2. Custom Scheme 설정
Project - Info 항목 최하단에 URL Types
항목이 있습니다.
Identifier
: 번들 아이디URL Schemes
: 호출될 Scheme
저는 scheme명을 번들 아이디와 동일하게 작성하였습니다.
3. AppDelegate 작성
// Swift
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return true
}
// Objective-C
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
return YES;
}
AppDelegate
로 이동하여 위 함수를 작성합니다.
그럼 이제 2번에서 설정한 scheme
을 통해 호출될 경우 해당 함수 로직을 수행하게 됩니다.
// Swift
if let scheme = url.scheme,
let bundleId = Bundle.main.bundleIdentifier {
switch scheme {
case bundleId:
// TODO
}
}
// Objective-C
NSString *bundleId = [[NSBundle mainBundle] bundleIdentifier];
if ([url.scheme isEqualToString:bundleId]) {
// TODO
}
2번에서 custom-scheme
을 bundleId
로 설정하였으므로 간단하게 비교하는 작업을 해주었습니다
이제 Safari에서 custom-scheme://
을 호출하면 앱이 실행됩니다
목적이 단순 호출인 경우 별다른 작업은 필요없으며 필요시 TODO 아래 내용을 채워주면 됩니다.
4. Parameter Parsing
// Swift
if let components = URLComponents(url: url, resolvingAgainstBaseURL: false) {
let qs = components.queryItems
}
// Objective-C
NSURLComponents *components = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:false];
NSArray *qs = components.queryItems;
1번에서 custom-scheme
과 parameter
가 있었는데 파라미터 파싱 방식입니다
첫 번째로 외부에서 호출한 url로 URLComponents
로 만들어줍니다
두 번째로 components에서 queryItems
를 추출합니다
queryItems는 URLQueryItem
이 배열로 담겨있음을 알 수 있습니다
URLQueryItem은 name
, value
프로퍼티를 가지고 있다는 것 또한 알 수 있습니다
[
{"name": "callback", "value": "appCalled"},
{"name": "message", "value": "앱 호출하기"}
]
즉, custom-scheme://?callback=appCalled&message=앱 호출하기
의 경우 위와 같이 표현됩니다
이제 이 데이터를 가지고 원하는 내용을 자유롭게 기술하면 됩니다
5. Parameter JSON으로 파싱하기
// Swift
if let qs = components.queryItems {
return Dictionary(uniqueKeysWithValues: qs.map { ($0.name, $0.value ?? "") })
}
// Objective-C
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
for (NSURLQueryItem *item in components.queryItems) {
[data setObject:item.value forKey:item.name];
}
여러 방법이 있겠지만 저는 이 방법으로 파싱하였습니다
map을 통해 queryItems를 순회하여 key, value 형태의 Dictionary
를 반환합니다