• Stars
    star
    298
  • Rank 139,663 (Top 3 %)
  • Language
    Objective-C
  • License
    MIT License
  • Created almost 11 years ago
  • Updated 5 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

iOS library for working with VK API, authorization through VK app, using VK functions

vk-ios-sdk

Library for working with VK API, authorizing through VK app, using VK API methods. Supported iOS from 8.0 Prepare for Using VK SDK

To use VK SDK primarily you need to create a new Standalone VK application here. Choose a title and confirm the action via SMS and you will be redirected to the application settings page. You will need your APP_ID to use the library. Fill in the App Bundle for iOS field.

Setup URL schema of Your Application

To authorize via VK App you need to setup a url-schema for your application, which looks like vk+APP_ID (e.g. vk1234567).

How to implement your own URL Scheme here, Also there is nice Twitter tutorial

Configuring application for iOS 9

iOS 9 changes the way of applications security and way of using unsecured connections. Basically, you don't have to change anything in transport security settings. But, if you're planing to use VK API with nohttps scope, you have to change security settings that way (in your Info.plist file):

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSExceptionDomains</key>
    <dict>
        <key>vk.com</key>
        <dict>
            <key>NSExceptionRequiresForwardSecrecy</key>
            <false/>
            <key>NSIncludesSubdomains</key>
            <true/>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
    </dict>
</dict>

We don't recommend using nohttps scope.

Also, for iOS 9 you have to add app schemas your app will use and check for canOpenURL:.

Add this to your Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>vk</string>
    <string>vk-share</string>
    <string>vkauthorize</string>
</array>

How to set up VK iOS SDK

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries like VK SDK in your projects. See the Getting Started guide for more information.

Podfile

platform :ios, '8.0'
target 'YourProjectName' do
  pod 'VK-ios-sdk'
end

Then import the project as module if your podfile contains use_frameworks! directive:

@import VK_ios_sdk;

Or import the main project header, if you're installing pods without use_frameworks! directive:

#import <VK-ios-sdk/VKSdk.h>

Installation with Carthage

iOS 8 and upper only

Add this to you Cartfile:

github "VKCOM/vk-ios-sdk" >= 1.4

See building instructions for Carthage here

Then import the main header.

#import <VKSdkFramework/VKSdkFramework.h>

Installation with framework project

If you're targeting iOS 8 and upper, you can use the SDK framework target. Add VK-ios-sdk.xcodeproj as sub-project to your project. Open your project in Xcode -> Go to General tab -> Find the Embedded Binaries section -> Click Add items (plus sign) -> And select VKSdkFramework.framework from the VK-ios-sdk project lastly import the main header:

#import <VKSdkFramework/VKSdkFramework.h>

Using SDK

SDK Initialization

  1. Put this code to the application delegate method
//iOS 9 workflow
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString *,id> *)options {
    [VKSdk processOpenURL:url fromApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]];
    return YES;
}

//iOS 8 and lower
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    [VKSdk processOpenURL:url fromApplication:sourceApplication];
    return YES;
}

Note: if you already have FaceBook SDK added and one of this methods returns [FBSDKDelegate ...] you can handle it

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {

    [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
    [VKSdk processOpenURL:url fromApplication:sourceApplication];
    return YES;
}
  1. Initialize VK SDK with your APP_ID for any delegate
VKSdk *sdkInstance = [VKSdk initializeWithAppId:YOUR_APP_ID];

Starting from version 1.3 there are two types of delegates available: common delegate and UI delegate. You can register as much common delegates, as you need, but an UI delegate may be only one. After the SDK initialization you should register delegates separately:

[sdkInstance registerDelegate:delegate];
[sdkInstance setUiDelegate:uiDelegate];

or

[[VKSdk initializeWithAppId:APP_ID] registerDelegate:delegate];

You will find full description of VKSdkDelegate and VKSdkUIDelegate protocols here or here

  1. You need to check, if there is previous session available, so call asynchronous method wakeUpSession:completeBlock:
NSArray *SCOPE = @[@"friends", @"email"];

[VKSdk wakeUpSession:SCOPE completeBlock:^(VKAuthorizationState state, NSError *error) {
    if (state == VKAuthorizationAuthorized) {
        // Authorized and ready to go
    } else if (error) {
        // Some error happened, but you may try later
    }
}];

You will find full list of available SCOPE permission here

Check out the VKAuthorizationState parameter. You can get several states:

  • VKAuthorizationInitialized – means the SDK is ready to work, and you can authorize user with +authorize: method. Probably, an old session has expired, and we wiped it out. This is not an error.
  • VKAuthorizationAuthorized - means a previous session is okay, and you can continue working with user data.
  • VKAuthorizationError - means some error happened when we tried to check the authorization. Probably, the internet connection has a bad quality. You have to try again later.
[VKSdk wakeUpSession:SCOPE completeBlock:^(VKAuthorizationState state, NSError *err) {
       if (state == VKAuthorizationAuthorized) {
           // authorized
       } else {
           // auth needed
       }
}];

User Authorization

If you don't have a session yet, you have to authorize user with a next method:

[VKSdk authorize:scope];

You have to conform to both VKSdkDelegate and VKSdkUIDelegate protocols to get appropriate methods called.

After the authorization, all common delegates will be called with a next method:

- (void)vkSdkAccessAuthorizationFinishedWithResult:(VKAuthorizationResult *)result;

VKAuthorizationResult contains some initial information: new access token object, basic user information, and error (if authorization failed). Complete documentation here

API Requests

VK API Request syntax

Below we have listed some examples for several request types.

  1. Plain request
VKRequest *usersReq = [[VKApi users] get];
  1. Request with parameters
VKRequest *audioReq = [[VKApi audio] get:@{VK_API_OWNER_ID : @"896232"}];
  1. Request with predetermined maximum number of attempts
VKRequest *postReq = [[VKApi wall] post:@{VK_API_MESSAGE : @"Test"}];
postReq.attempts = 10;
//or infinite
//postReq.attempts = 0;

It will take 10 attempts until succeeds or an API error occurs

  1. Request that calls any method of VK API
VKRequest *getWall = [VKRequest requestWithMethod:@"wall.get" andParameters:@{VK_API_OWNER_ID : @"-1"}];
  1. Request that uploads a photo to a user's wall
VKRequest *request = [VKApi uploadWallPhotoRequest:[UIImage imageNamed:@"my_photo"] parameters:[VKImageParameters pngImage] userId:0 groupId:0 ];

Request firing

[audioReq executeWithResultBlock:^(VKResponse *response) {
        NSLog(@"Json result: %@", response.json);
    } errorBlock:^(NSError * error) {
    if (error.code != VK_API_ERROR) {
        [error.vkError.request repeat];
    } else {
        NSLog(@"VK error: %@", error);
    }
}];

Error Handling

Every request can return NSError with domain equal to VKSdkErrorDomain. SDK can return networking error or internal SDK error (e.g. request was canceled). Category NSError+VKError provides vkError property that describes error event. Compare error code with the global constant VK_API_ERROR. If they are equal that means you process vkError property as API error. Otherwise you should handle an http error.

SDK can handle some errors (e.g., captcha error, validation error). Appropriate ui delegate method will be called for this purpose. Below is an example of captcha error processing:

- (void)vkSdkNeedCaptchaEnter:(VKError *)captchaError
{
    VKCaptchaViewController *vc = [VKCaptchaViewController captchaControllerWithError:captchaError];
    [vc presentIn:self];
}

Batch Processing Requests

SDK allows to execute several unrelated requests at the one call (aka Batch Request).

  1. Prepare requests
VKRequest *request1 = [[VKApi audio] get];
request1.completeBlock = ^(VKResponse *) { ... };

VKRequest *request2 = [[VKApi users] get:@{VK_USER_IDS : @[@(1), @(6492), @(1708231)]}];
request2.completeBlock = ^(VKResponse *) { ... };
  1. Merge requests into one
VKBatchRequest *batch = [[VKBatchRequest alloc] initWithRequests:request1, request2, nil];
  1. Fire the obtained request
[batch executeWithResultBlock:^(NSArray *responses) {
        NSLog(@"Responses: %@", responses);
    } errorBlock:^(NSError \*error) {
        NSLog(@"Error: %@", error);
}];
  1. The result of each method returns to a corresponding completeBlock. Response array contains result of the requests in order they have been passed.

Working with Share dialog

Share dialog allows you to create a user friendly dialog for sharing text and photos from your application directly to VK. See the Share dialog usage example:

VKShareDialogController *shareDialog = [VKShareDialogController new]; //1
shareDialog.text         = @"This post created using #vksdk #ios"; //2
shareDialog.vkImages     = @[@"-10889156_348122347",@"7840938_319411365",@"-60479154_333497085"]; //3
shareDialog.shareLink    = [[VKShareLink alloc] initWithTitle:@"Super puper link, but nobody knows" link:[NSURL URLWithString:@"https://vk.com/dev/ios_sdk"]]; //4
[shareDialog setCompletionHandler:^(VKShareDialogControllerResult result) {
    [self dismissViewControllerAnimated:YES completion:nil];
}]; //5
[self presentViewController:shareDialog animated:YES completion:nil]; //6
  1. Create an instance of the dialog controller as usual

  2. Attach some text information to a dialog. Notice that users can change this information

  3. Attach images uploaded to VK earlier. If you want user to upload a new image use uploadImages property

  4. Attach link at your pages

  5. Set the dialog completion handler

  6. Present the dialog view controller to your view controller

Working with share activity

VK SDK provides a special class to work with UIActivityViewController - VKActivity.

Pay attention to the fact, that a VK App has it own Share extension since version 2.4. Since version 2.5 it will support special URL scheme to check if Share extension is available. You should call [VKActivity vkShareExtensionEnabled] method to remove VKActivity from activities list, if a VK share extension is available.

Check the example below to understand how it works:

NSArray *items = @[[UIImage imageNamed:@"apple"], @"Check out information about VK SDK" , [NSURL URLWithString:@"https://vk.com/dev/ios_sdk"]]; //1
UIActivityViewController *activityViewController = [[UIActivityViewController alloc]
                                                    initWithActivityItems:items
                                                    applicationActivities:@[[VKActivity new]]]; //2
[activityViewController setValue:@"VK SDK" forKey:@"subject"]; //3
[activityViewController setCompletionHandler:nil]; //4
if (VK_SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")) {
    UIPopoverPresentationController *popover = activityViewController.popoverPresentationController;
    popover.sourceView = self.view;
    popover.sourceRect = [tableView rectForRowAtIndexPath:indexPath];
} //5
[self presentViewController:activityViewController animated:YES completion:nil]; //6

Let's go through the example step-by-step

  1. Prepare your share information - UIImage, NSString and NSURL. That kind of information may be shared through VK

  2. Prepare UIActivityViewController with a new application VKActivity

  3. Set additional properties for activityViewController

  4. Set completion handler for activityViewController

  5. Check if you're running iOS 8 or upper. If user is using iPad, you have to present the activity controller in a popover otherwise you'll get system error

  6. Present the activity controller as usual

More Repositories

1

kphp

KPHP — a PHP compiler
C++
1,322
star
2

VKUI

VKUI – это набор React-компонентов, с помощью которых можно создавать интерфейсы, внешне неотличимые от наших iOS и Android приложений.
TypeScript
995
star
3

YouTokenToMe

Unsupervised text tokenizer focused on computational efficiency
C++
951
star
4

noverify

Pretty fast linter (code static analysis utility) for PHP
Go
667
star
5

vk-android-sdk

Android library for working with VK API, authorization through VK app, using VK functions.
Kotlin
458
star
6

vk-java-sdk

Java library for working with VK API
Java
290
star
7

vk-api-schema

JSON Schema of VK API
Shell
206
star
8

statshouse

StatsHouse is a highly available, scalable, multitenant monitoring system
C
206
star
9

vk-php-sdk

PHP library for working with VK API
PHP
204
star
10

vkompose

Kotlin Compiler Plugins, an IDEA Plugin, and a Detekt Rule that will help to improve your experience with Jetpack Compose
Kotlin
190
star
11

kittenhouse

Go
185
star
12

lighthouse

Lightweight interface for ClickHouse
JavaScript
185
star
13

joy4

Golang audio/video library and streaming server
Go
180
star
14

nocolor

Validate the architecture of your PHP project based on the concept of function colors
Go
161
star
15

nginx-quic

C
151
star
16

KNet

Android network library with QUIC protocol supporting.
Kotlin
148
star
17

nocc

A distributed C++ compiler: like distcc, but faster
Go
142
star
18

bot-example-php

Пример бота для VK
PHP
134
star
19

icons

Набор SVG иконок, представленный в виде React компонентов.
JavaScript
124
star
20

vk-bridge

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web
TypeScript
70
star
21

php-parser

PHP parser written in Go
Go
69
star
22

modulite

A plugin for PHPStorm that brings modules to the PHP language
Kotlin
65
star
23

vk-qr

VK QR Code generator library
TypeScript
58
star
24

create-vk-mini-app

Create VK Apps with no build configuration.
TypeScript
53
star
25

vk-miniapps-deploy

NPM module for deploy VK Mini Apps on VK hosting
JavaScript
49
star
26

kphpstorm

A PhpStorm plugin that makes IDE understand KPHP specifics
Kotlin
41
star
27

vkui-tokens

TypeScript
39
star
28

fastXDM

fast library for cross-domain messaging
JavaScript
39
star
29

node-vk-call

Simple API wrapper for VK.com social network
JavaScript
35
star
30

elephize

Typescript to PHP translation tool
TypeScript
33
star
31

vk-streaming-api

Go
33
star
32

vk-mini-apps-api

The official package for quick and easy development of VK Mini Apps
TypeScript
28
star
33

vk-mini-apps-router

TypeScript
27
star
34

Appearance

JavaScript
26
star
35

vkid-android-sdk

Kotlin
25
star
36

vkjs

VK shared JS libs
TypeScript
23
star
37

vk-router

TypeScript
22
star
38

vk-windowsphone-sdk

VK SDK for Windows Phone
C#
22
star
39

admstorm

PhpStorm plugin aimed at simplifying tasks at the junction of the local repository and the repository on the dev server
Kotlin
20
star
40

vk-unity-sdk

C#
20
star
41

vk-tunnel-client

TypeScript
19
star
42

kive

Go
19
star
43

tl

C++
18
star
44

vkdata-sketchplugin

Sketch plugin for using data from your account at vk.com
JavaScript
17
star
45

vk-apps-launch-params

Пример работы с параметрами запуска
JavaScript
17
star
46

nginx-http-vkupload-module

C
16
star
47

kphp-polyfills

PHP implementations of functions supported by KPHP natively (a Composer package)
PHP
15
star
48

superappkit-android-demo

Kotlin
15
star
49

vkid-web-sdk

TypeScript
15
star
50

vk-mini-apps-examples

TypeScript
15
star
51

IOSDevice

A set of hacks and workarounds for iOS Safari & Co.
JavaScript
14
star
52

docker-emulator-android

Dockerfile
13
star
53

modulite-phpstan

Bring modules into PHP and PHPStan
PHP
13
star
54

vk-apps-tensorflow-example

VK apps + tensorflow-js demo app
JavaScript
12
star
55

api-schema-typescript-generator

TypeScript
11
star
56

vkid-ios-sdk

Swift
11
star
57

api-schema-typescript

TypeScript
10
star
58

VKSDK-iOS

Swift
10
star
59

Delegate

Python
10
star
60

engine-go

Common libraries for our go engines (microservices)
Go
10
star
61

vk-direct-games-example

JavaScript
10
star
62

vk-ios-urlprotocol-example

This is an example iOS app with custom URLProtocol
Swift
10
star
63

swc-plugin-css-modules

Rust
9
star
64

vk-bridge-mock

The VK Bridge mock library
TypeScript
9
star
65

ktest

Test and benchmark KPHP code
Go
9
star
66

vk-ads-retargeting-demo

Демонстрация JavaScript API ретаргетинга ВКонтакте
HTML
8
star
67

eslint-config

JavaScript
8
star
68

useWeb3

JavaScript
8
star
69

TL-Schema-idea-plugin

Plugin for JetBrains products for coloring TL Schema files
Java
8
star
70

vk-connect-promise

A package for integrating VK Mini Apps with official VK clients for iOS, Android and Web with events based on promises
JavaScript
8
star
71

torch_mobile

Torch7 for mobile devices
C
7
star
72

vkui-benchmarks

JavaScript
7
star
73

noverify-phpstorm

NoVerify plugin for PhpStorm
Kotlin
6
star
74

superappkit-ios

Ruby
6
star
75

swc-plugin-transform-remove-imports

Rust
6
star
76

VideoPlayer-iOS

Swift
6
star
77

statshouse-go

StatsHouse client library for Go
Go
6
star
78

create-vkui-app

JavaScript
6
star
79

m3u8

Parser and generator of M3U8-playlists for Apple HLS.
Go
5
star
80

nginx-statshouse-module

StatsHouse module for nginx
C
5
star
81

statshouse-cpp

StatsHouse client library for C++
C++
5
star
82

statshouse-php

StatsHouse client library for PHP and KPHP
PHP
5
star
83

stylelint-config

TypeScript
4
star
84

statshouse-java

Java
4
star
85

modulite-example-project

This example project contains some Modulite errors, detected by IDE, PHPStan, and KPHP
PHP
4
star
86

kphp-tools

A set of independent tools to work with KPHP compiled code
JavaScript
4
star
87

kphp-snippets

Libraries written in PHP aimed to be compiled with KPHP
PHP
4
star
88

vk-mini-apps-course-frontend

TypeScript
4
star
89

graph-cache

Easy way to build and maintain persistent dependency graph for any type of files/languges
JavaScript
4
star
90

gulp-portal

JavaScript
4
star
91

sprites

Module for generate SVG sprites and PNG fallback
JavaScript
4
star
92

swc-plugin-pre-paths

Rust
3
star
93

mask-assets

AngelScript
3
star
94

mini-apps-analytics

TypeScript
3
star
95

vk-apps-currency

JavaScript
3
star
96

eslint-plugin

JavaScript
3
star
97

vk-apps-qr

VK Apps + QR demo app
JavaScript
2
star
98

ktest-script

PHP
2
star
99

mvk-mini-apps-scroll-helper

JavaScript
2
star
100

prettier-config

JavaScript
2
star