Developing with the LINE SDK for iOS
You can integrate your iOS apps with LINE using the LINE SDK for iOS. This page explains how to embed the LINE SDK for iOS in your iOS apps.
Prerequisites
The following information is required to use the LINE SDK.
| Information | Description |
|---|---|
| Channel ID | Identifier issued when creating your Channel. For information on how to create Channels, see Creating a Channel. |
The following steps assume that ARC (Objective-C Auto Reference Counting) of your project’s build settings is set to Yes. If your project has ARC set to No, add the appropriate release or retain processes.
Downloading the LINE SDK
The LINE SDK can be downloaded from the following link.
Download the LINE SDK for iOS
Select your Channel from the list on the left.
Click Download SDK.
Click the link of the SDK archive file.
Note: The download link is displayed only after the Channel status becomes DEVELOPING.
Save the archive file into any directory. Unzip the file.
LINE starter application
The LINE starter application provides you with all the elements you need to start integrating the LINE SDK into your app.
Download the LINE starter application from the following link.
Project settings
To integrate your iOS app with LINE, you must add the LINE SDK for iOS to your Xcode project. The following settings must also be configured.
Framework links included in the LINE SDK
The LINE SDK for iOS is distributed in both framework and bundle formats. These will be linked to the app. The following frameworks and bundle can be found in the unzipped LINE SDK directory.
| Directory and file name | Description |
|---|---|
| LineAdapter.framework | Provides the core functions for integrating with LINE. |
| LineAdapterLogin.framework | Provides the function for email/ID/password input and authentication |
| LineAdapterUI.framework | Provides the authentication UI |
| LineAdapterUI.bundle | Required for LineAdapterUI.framework |
Click “+” in the Link Binary With Libraries item on the Project Build Phases page in Xcode. Then click Add Other… to add the three directories above and to link the LINE SDK frameworks with your project.
Other required framework links
Add and link the following required frameworks to Link Binary With Libraries using the same steps as above.
| Framework name | Description |
|---|---|
| Foundation.framework | Required in iOS apps. |
| UIKit.framework | Required in iOS apps. |
| Security.framework | Used in LineAdapter.framework. |
| CoreTelephony.framework | Used in LineAdapter.framework. |
| CoreGraphics.framework | Used in LineAdapterUI.framework. |
| CoreText.framework | Used in LineAdapter.framework. |
Other settings
Configure the following settings in your project.
- Linker flag settings
- URL Types settings
- Create configuration file
Select All on the Build Settings screen of your project and find the Other Linker Flags item. Add -ObjC to the value.
Next, select URL Types. If LINE is installed on the user’s device, it will be launched by the LINE SDK to authenticate and authorize the user. After the user logs in to LINE and agrees to the permissions, LINE will return control to your iOS app and pass on the authentication results. The custom URL scheme used in this process is named using the following rule.
- “line3rdp.” + Bundle Identifier
A custom URL scheme must be added to your project. Open the URL Types item on the Info page of your project and enter your custom URL scheme in the URL Schemes field.
Finally, create a configuration file. The configuration file defines the Channel ID. For example:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ChannelId</key>
<string>12345</string>
</dict>
</plist>
Add the file above with the name “LineAdapter.plist” into Bundle.
Settings for iOS 9 or later
If you are compiling your app with iOS SDK 9.0 or later, add the following settings.
Whitelisting the LINE app
Add the following to the plist to whitelist the LINE app allowing it to be launched.
<key>LSApplicationQueriesSchemes</key>
<array>
<string>lineauth</string>
<string>line3rdp.$(APP_IDENTIFIER)</string>
</array>
Whitelisting LINE domains
Add the following to the plist to whitelist LINE domains.
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>obs.line-apps.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>dl.profile.line.naver.jp</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>lcs.naver.jp</key>
<dict>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>scdn.line-apps.com</key>
<dict>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>access.line.me</key>
<dict>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>api.line.me</key>
<dict>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
Initialization
Integration of the iOS app with LINE is carried out using the LINE SDK. The following describes the initialization process.
Adding processes to the UIApplicationDelegate implemented class
If LINE is installed on the user’s device, it will be launched by the LINE SDK to perform the authentication and authorization process. After the user logs in to LINE and agrees to the permissions, LINE will return control to your app.
Add the following processes to the UIApplicationDelegate implemented class to let your app receive authentication results.
#import <LineAdapter/LineAdapter.h>
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
// Add the following line
[LineAdapter handleLaunchOptions:launchOptions];
return YES;
}
// Add the following two methods
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [LineAdapter handleOpenURL:url];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
return [LineAdapter handleOpenURL:url];
}
Generation of LineAdapter instances
Generate the LineAdapter class instance to use the SDK. For example, to use the LINE SDK at the ViewController class, declare the instance variable in the ViewController.h header file as shown here:
...
@class LineAdapter;
@interface ViewController ()
{
...
LineAdapter *mAdapter;
}
Next, generate the LineAdapter class instance in the ViewController.m file. Because the authentication and authorization results are transmitted via the Notification Center, the registration process to receive them must be performed at the same time. The following example assumes that Storyboard is in use and therefore overrides the initWithCoder method. If Storyboard is not in use, perform the following processes at the appropriate init methods.
...
#import <LineAdapter/LineAdapter.h>
#import <LineAdapterUI/LineAdapterUI.h>
...
@implementation ViewController
...
- (void)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self)
{
...
mAdapter = [[LineAdapter alloc] initWithConfigFile];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(lineAdapterAuthorizationDidChange:)
name:LineAdapterAuthorizationDidChangeNotification object:nil];
}
return self;
}
The initWithConfigFile: method will return the same instance as long as the configuration values are the same. Do not release the LineAdapter instance if ARC is disabled.
The example above specifies that LineAdapterAuthorizationDidChangeNotification from NSNoticationCenter is received with the lineAdapterAuthorizationDidChange: method after the authentication process.
Login
The authentication and authorization process (user logging in and agreeing to the permissions) is called using the LineAdapter class instance.
The following is used to make a request to LINE for authentication and authorization. Add this to the event handler method when the login button is clicked.
if ([adapter isAuthorized])
{
// If the authentication and authorization process has already been performed
}
else
{
if ([mAdapter canAuthorizeUsingLineApp])
{
// Authenticate with LINE application
[adapter authorize];
}
else
{
// Authenticate with WebView
UIViewController *viewController;
viewController = [[[LineAdapterWebViewController alloc] initWithAdapter:adapter
withWebViewOrientation:kOrientationAll] autorelease];
[[viewController navigationItem] setLeftBarButtonItem:[LineAdapterNavigationController
barButtonItemWithTitle:@"Cancel" target:self action:@selector(cancel:)]];
UIViewController *navigationController;
navigationController = [[[LineAdapterNavigationController alloc]
initWithRootViewController:viewController] autorelease];
[self presentViewController:navigationController animated:YES];
}
}
The isAuthorized value of the LineAdapter class confirms whether the user has been authenticated and authorized and whether an access token is available. If not, the LineAdapter class calls the authorize method to have LINE perform the authentication and authorization process.
The canAuthorizeUsingLineApp: method determines whether LINE is installed on the user’s device. If it returns YES, the authorize method is called to authenticate and authorize the user. If it returns NO, the WebView in your iOS app performs the authentication and authorization process instead of LINE.
The above code constructs the UI for the authentication and authorization process using the LineAdapterWebViewController and LineAdapterNavigationController classes. Make sure to specify the text label of the button used to cancel the authentication and authorization process in the barButtonItemWithTitle argument and the callback method that is called when that button is tapped in the action argument. To hide the authentication and authorization UI at the callback method:
- (void)cancel:(id)aSender
{
[self dismissViewControllerAnimated:YES completion:nil];
}
The authentication and authorization results appear in the Notification Center. The results can be received in the callback method added to the Notification Center after the LineAdapter instance is generated. Example:
- (void)lineAdapterAuthorizationDidChange:(NSNotification*)aNotification
{
LineAdapter *_adapter = [aNotification object];
if ([_adapter isAuthorized])
{
// Connection completed to LINE.
}
else
{
NSError *error = [[aNotification userInfo] objectForKey:@"error"];
if (error)
{
NSString *errorMessage = [error localizedDescription];
NSInteger code = [error code];
if (code == kLineAdapterErrorMissingConfiguration)
{
// URL Types is not set correctly
}
else if (code == kLineAdapterErrorAuthorizationAgentNotAvailable)
{
// The LINE application is not installed
}
else if (code == kLineAdapterErrorInvalidServerResponse)
{
// The response from the server is incorrect
}
else if (code == kLineAdapterErrorAuthorizationDenied)
{
// The user has cancelled the authentication and authorization
}
else if (code == kLineAdapterErrorAuthorizationFailed)
{
// The authentication and authorization has failed for an unknown reason
}
}
}
}
Extract the LineAdapter class instance from the NSNotification class instance passed from the callback method argument (if you can access the LineAdapter class instance held as the instance variable, you can use that too). Determine whether the authentication and authorization process has been completed using the isAuthorized method. Because the access token information is saved in Keychain in the LineAdapter class, it can be retrieved using the LineAdapter class and does not need to be saved in the app.
Error codes and messages
If an error occurs during the authentication and authorization process, the isAuthorized method will return NO. In this case, you can retrieve the following error information from the NSNotification class instance.
- Error code
- Error message
Error codes are retrieved from the NSError class instance. The error codes and their meanings are explained below:
| Code | Meaning |
|---|---|
| kLineAdapterErrorMissingConfiguration | URL types not set correctly and LINE cannot be called. |
| kLineAdapterErrorAuthorizationAgentNotAvailable | LINE not installed and the authentication and authorization process cannot be performed. |
| kLineAdapterErrorInvalidServerResponse | Response from the LINE server incorrect and authentication and authorization process cannot continue. |
| kLineAdapterErrorAuthorizationDenied | User has canceled the login process or agreement to the permissions. |
| kLineAdapterErrorAuthorizationFailed | Authentication and authorization process failed due to an unknown reason. |
Error messages are retrieved using the localizedDescription method of the NSError class. Appropriate error handling must be implemented using this information.
Note: Do not display the error message as is.
Automatically refreshing access tokens
Every access token has an expiration date. Your app can use an access token up until the expiration date. Once expired, the access token will be rendered invalid and API calls will fail. However, you can have the access token reissued with a refresh token. The LINE SDK for iOS automatically keeps access tokens up-to-date by automatically refreshing access tokens when they expire. This is executed when calling an API method.
The LINE SDK for iOS has three states.
- Not connected. The access token and refresh token are both invalid.
[mAdapter isAuthorized] == NO - Connected. The access token and refresh token are stored.
[mAdapter isAuthorized] == YES - Expired. The access token is invalid but the refresh token is valid.
If an API method is called in the third situation, the LINE SDK for iOS refreshes the token depending on the response from the API server. If the refresh process fails, LineAdapterNoLongerAuthorizedNotification is sent and the SDK shifts to the first state. If the refresh process is successful, LineAdapterRefreshedTokenNotification is sent and the SDK shifts to the second state.
Logout
If you want to add a logout feature to your iOS app, you must make sure the information in the access token is invalidated. There are two methods to void the access token:
- Call an API via the back-end server (for more information, refer to Logout)
- Call the invalidation function from the SDK
To void the access token and other information from the SDK, call the unauthorize method in the LineAdapter class.
[adapter unauthorize];
All access token information saved in Keychain is also deleted.
Calling APIs
Certain APIs can be used directly with the LINE SDK for iOS. The LINE SDK for iOS provides methods to call these APIs. These methods are defined in the LineApiClient interface. You can retrieve the LineApiClient instance from LineAdapter.
Because API calls are executed asynchronously, you must register a block to receive the results of API calls. The following shows how to call an API to retrieve a user’s profile information.
[[mAdapter getLineApiClient] getMyProfileWithResultBlock:^(NSDictionary *aResult, NSError *aError)
{
if (aResult)
{
// API call was successfully.
NSLog(@"displayName : %@", data[@"displayName"]);
NSLog(@"id : %@", data[@"id"]);
NSLog(@"mid : %@", data[@"mid"]);
NSLog(@"pictureUrl : %@", data[@"pictureUrl"]);
NSLog(@"profileImageUrl : %@", data[@"profileImageUrl"]);
NSLog(@"statusMessage : %@", data[@"statusMessage"]);
[UIAlertView showAlert:[data description]];
}
else
{
// API call failed.
NSDictionary *userInfo = [aError userInfo];
NSLog(@"statusCode : %@", userInfo[@"statusCode"]);
NSLog(@"statusMessage : %@", userInfo[@"statusMessage"]);
}
}];
If an error occurs, the reason for the error will be passed as an aError argument. The error object contains two sets of information: domain and code. There are two possible domains:
- NSURLErrorDomain: General error.
- LineAdapterErrorDomain: Error between the SDK and API server.
The possible combinations of domains and codes are as follows.
| Domain | Code | Meaning |
|---|---|---|
| NSURLErrorDomain | kCFURLErrorNotConnectedToInternet | Not connected to the network. |
| LineAdapterErrorDomain | kLineAdapterErrorAuthorizationExpired | Access token has expired. |
| LineAdapterErrorDomain | kLineAdapterErrorInvalidServerResponse | Resulting JSON string invalid. |
| LineAdapterErrorDomain | kLineAdapterErrorAccessTokenIsNotAvailable | API called without a valid access token. |
You can get more information from userInfo which has two values: status code and status message. Errors must be handled appropriately by your app.