SwiftyVK makes it easy to interact with social network "VKontakte" API for iOS and OSX.
On this page:
- Requirements
- Integration
- Getting started
- API Requests
- Parsing response
- Error handling
- Upload files
- Longpoll
##Requirements
- Swift 3.0+
- iOS 8.0+ / OSX 10.10+
- Xcode 8.0+
##Integration ###Manually
- Just drag SwiftyVK.framework or include the whole SwiftyVK.xcodeproj to project
- Link SwiftyVK.framework to application in Target preferences -> General -> Embedded binaries.
###CocoaPods
You can use CocoaPods to install SwiftyVK
by adding it to Podfile
:
use_frameworks!
target 'MyApp' do
pod 'SwiftyVK', :git => 'https://github.com/WE-St0r/SwiftyVK.git'
end
###Carthage
You can use Carthage to install SwiftyVK
by adding it to Cartfile
:
github "WE-St0r/SwiftyVK"
##Getting started ###Import and implementation
Import SviftyVK to Swift file:
import SwiftyVK
Implement VKDelegate
protocol and all its functions in custom class. For example:
class YourClass: Superclass, VKDelegate {
func vkWillAuthorize() -> [VK.Scope] {
//Called when SwiftyVK need autorization permissions.
return //an array of application permissions
}
func vkDidAuthorizeWith(parameters: Dictionary<String, String>) {}
//Called when the user is log in.
//Here you can start to send requests to the API.
}
func vkDidUnauthorize() {
//Called when user is log out.
}
func vkAutorizationFailedWith(error: VK.Error) {
//Called when SwiftyVK could not authorize. To let the application know that something went wrong.
}
func vkShouldUseTokenPath() -> String? {
//Called when SwiftyVK need know where a token is located.
return //Path to save/read token or nil if should save token to UserDefaults
}
func vkWillPresentView() -> UIViewController {
//Only for iOS!
//Called when need to display a view from SwiftyVK.
return //UIViewController that should present autorization view controller
}
func vkWillPresentView() -> NSWindow? {
//Only for OSX!
//Called when need to display a window from SwiftyVK.
return //Parent window for modal view or nil if view should present in separate window
}
}
See full implementation in Example project
###Initialization
- Create new standalone application and get
application ID
- Init SwiftyVK with
application ID
andVKDelegate
object:
VK.start(appID: applicationID, delegate: VKDelegate)
###User authorization
- Implement
vkWillAuthorize()
function inVKDelegate
and return application permissions. - Just call:
VK.logIn()
- And user will see authorization dialog.
After this, you will check VK state:
VK.state // will be unknown, configured, authorization, authorized
And if state == authorized, send your requests to API (:
###Authorization with VK App For authorization with official VK application for iOS, you need:
1. In Xcode -> Target -> Info
- Add new URL Type with URL identifier to URL Types
vk$YOUR_APP_ID$
(e.g. vk1234567890) - Add app schemas to Info.plist file:
<key>LSApplicationQueriesSchemes</key>
<array>
<string>vkauthorize</string>
<string>vk$YOUR_APP_ID$</string>
</array>
2. In https://vk.com/apps?act=manage -> Edit App -> Settings
- Set
App Bundle ID for iOS
to yourApp Bundle
in Xcode -> Target -> Bundle Identifier (e.g. com.developer.applicationName)
3. Add this code to appDelegate
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
VK.processURL(url, options: options)
return true
}
4. Test it!
If user deny authorization with VK App, SwiftyVK show standart authorization WebView in your app.
##API Requests ###Syntax The call requests is as follows VK.methodGrop.methodName.
For example, send request with parameters and response processing:
let req = VK.API.Users.get([VK.Arg.userId : "1"])
req.httpMethod = .Get
req.successBlock = {response in print(response)}
req.errorBlock = {error in print(error)}
req.send()
Or a bit shorter:
let req = VK.API.Users.get([VK.Arg.userId : "1"]).send(
method: .Get
onSuccess: {response in print(response)},
onError: {error in print(error)}
)
###Custom requests You may also send special requests, such as:
- Request with custom method path:
VK.API.custom(method: "users.get", parameters: [VK.Arg.userId : "1"])
- Execute request returns "Hello World":
VK.API.execute("return \"Hello World\"")
- Remote execute stored application code:
VK.API.remote(method: "YourRemoteMethodName")
###Request properties
The requests have several properties that control their behavior. Their names speak for themselves, but just in case I describe them:
Property | Default | Description |
---|---|---|
id |
1... | Automatically generated id. |
httpMethod |
.GET | HTTP protocol method. |
successBlock |
empty | This code block will be executed when the response to the request. |
errorBlock |
empty | This code block will be executed, if during execution of the response fails. |
progressBlock |
empty | This code block is executed when the file is loaded. It is called every time the server sent the next part of the file. |
asynchronous |
true | Specifies whether the control returns after sending the request immediately or only after receiving the response. By default the requests are asynchronous and control returns immediately. Sometimes you may need to send synchronous requests, but it is not necessary to do this in the main thread!. |
maxAttempts |
3 | The number of times can be resend the request automatically, if during its execution the error occurred. 0 == infinity attempts. |
timeout |
10 | How long in seconds a request will wait for a response from the server. If the wait is longer this value, the generated request error. |
cancelled |
false | If user cancell request it will true |
catchErrors |
true | Whether to attempt SwiftyVK to handle some query errors automatically. Among these errors include the required authentication, captcha, exceeding the limit of requests per second. |
language |
system | The language, which will return response fields. |
log |
[String] | Request sending log. |
###Default properties
In addition to the settings of each individual request, you can set global settings for SwiftyVK. You need to contact structure VK.defaults
. Some fields completely duplicate the properties of requests and will be assigned to the request when it is initialized, and the other presented only in a global context.
Property | Default | Description |
---|---|---|
apiVersion |
>5.44 | Returns used VK API version |
maxRequestsPerSec |
3 | The maximum number of requests that can be sent per second. Here you can read more in the section "Limitations and recommendations". |
##Parsing response
Responses to requests come in the form of text in JSON format. To present the data as objects, SwiftyVK uses the SwiftyJSON library. You can refer to the documentation of the library. Here I'll describe only a short example.
In our request example about the syntax that will return the response:
[
{
"id" : 1,
"first_name" : "Pavel",
"last_name" : "Durov"
}
]
It contains an array of users which we have access to 3 fields. Suppose that we want to get all user data into separate variable. We can do this:
var id = response[0,"id"].intValue //1
var firstName = response[0,"first_name"].stringValue //Pavel
var lastName = response[0,"last_name"].stringValue //Durov
And that's all You need. If You want to learn more, check out the SwiftyJSON documentation.
##Error handling
In the process of request execution something can go wrong, as expected. In this case, an error is generated. SwiftyVK offers two ways of working with errors:
catchErrors == false
: SwiftyVK is always called the block error handling and you get to decide what to do with the error.
But sometimes it so happens that the query is executed when the user is not authorized, requires validation / captcha entering, or simply exceeded the number of requests per second. To automatically resolve these errors is second case.
catchErrors == true
: SwiftyVK first try to handle the error. If it contains codes 5, 6, 9, 10, 14, 17, e.t.c. which arise in the above cases, the request is resended again after a short delay, or the user will see a dialogue offering to authorize, validate, or enter the captcha. If the error persists, and the number of resends of request more thanmaxAttempts
, it will call the error block.
##Upload files
SwiftyVK allows you to easily upload files in one request by combining standard requests to VK API. Use methods in VK.Upload
section. Let's see how you can quickly upload photos to an album:
//Get data of image
let data = NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("image", ofType: "jpg")!)!
//Crete media object to upload
let media = Media(imageData: data, type: .JPG)
//Upload image to wall
let req = VK.API.Upload.Photo.toWall.toUser(media, userId: "1234567890")
req.progressBlock = {done, total in print("SwiftyVK: uploadPhoto progress: \(done) of \(total))")}
req.successBlock = {response in print("SwiftyVK: uploadPhoto success \n \(response)")}
req.errorBlock = {error in print("SwiftyVK: uploadPhoto fail \n \(error)")}
req.send()
)
This way you can download all the other supported Vkontakte file types. Can see the implementation of other types of loading in the library tests.
Keep in mind that in some cases, such as uploading photos to a message, using this method, you just load the file to the server and get its ID. To send a message with photo, you need to add photo ID to the message.
##Longpoll
If you want to use Longpoll to receive updates, SwiftyVK allows you to easily do this, as it contains tool for working with Longpoll.
VK.LP sends requests every 25 seconds and waits for a response. When the response is received, VK.LP send a notification and send next request. If the device goes to sleep, the app becomes inactive, or is lost the network, VK.LP stops and again starts working when the state is changed to the opposite. This process is fully automatic. All you need are two methods and one parameter:
VK.LP.start() //Start updating
VK.LP.active //Longpoll status
VK.LP.stop() //Stop updating
And notifications types in VK.LP.notifications
whose codes correspond to the codes here
To subscribe to the notification you just need to use standard observer:
NotificationCenter.default.addObserver(self, selector: #selector(UPDATE), name: VK.LP.notifications.type4, object: nil)