Downloading files using Alamofire in OperationQueue

Operation object might be deallocated while Alamofire performing async download of a file inside. So if you need to do something that depends of your Operation class property you can override isFinished property to wait while callback will be called:

class TestOperation: Operation {
  private var downloaded: Bool = false
  let urlString: String
  override var isFinished: Bool {
    get {
      return downloaded
  // MARK: - Init
  init(urlString: String) {
    self.urlString = urlString
  override func main() {
    if self.isCancelled {return }
  override func start() {
    if self.isCancelled { return }
    print("Starting downloading from url: \(urlString)")
    let destination = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0], to: destination)
      .response { [unowned self] response in
        defer {
          // operation will be deallocated after setting true
          self.downloaded = true
        if self.isCancelled { return }
        print("Finished downloading from url: \(self.urlString)")
// create queue 
var downloadQueue: OperationQueue = {
  var queue = OperationQueue() = "Download queue"
  return queue
// create operation and add to queue
let op = TestOperation(urlString: "done")


comment comments

Benchmarks: Vapor 3 vs. Vapor 2

After migrating (almost rewriting) my small project from Vapor 2 to Vapor 3 I've run benchmarks to compare performance. I didn't run benchmarks for the last version of Vapor 2.x so I will compare Vapor 2.1.0 to results of Vapor 3.1.0.

My server:

  • 2 GB RAM
  • 1 CPU Core
  • SSD
  • 125 MBPS Out
  • Ubuntu 16.04.2 LTS
  • CouchDB

Benchmark from other server was launched as:

wrk -t4 -c20 -d5m https://my_url

API just gets some data from CouchDB and returns it as JSON. Vapor project was compiled with Swift 4.2.

Total requests


Requests per second


Average Latency


Memory usage


Vapor 3 was rewriten and now it's based on Apple's NIO. It's faster than Vapor 2 but using more memory which is not critical.

Previous benchmarks:
Benchmarks: Vapor 2 vs. Vapor 1
Benchmarks for Vapor 1.2.5
Swift Backend with CouchDB: Kitura vs. Vapor vs. Node.js

comment comments
local_offer swift backend vapor ubuntu

Select like a Boss для Safari в Mac App Store

24 сентября вышла новая версия macOS - Mojave. А в месте с ней и Safari 12, который теперь поддерживает установку расширений только из Mac App Store. Пришлось запилить приложение с расширением.


comment comments

JPG to HEIF converter

Today I've decided to experiment with HEIF that was introduced by Apple with macOS 10.13 and iOS 11. They said that it has the same quality with much lower file size.

It's supported in last versions of macOS and iOS and last models of iPhone can take pictures in that format. 

I'm thinking about compressing my home archive of photos and videos. I was experimenting with HEVC (H.265) and results was great - I had reduced size of my videos with endoding them to HEVC with awesome util called HandBrake.

I found the only way to convert JPG to HEIF (which has HEIC extension). It's possible with Preview app from macOS. But it was interesting for me if I can do it by myself in Swift. So I did :)

My folder with 64 photos from my action camera was 203 mb in JPG format. And it's only 31.3 mb in HEIC.

macOS and iOS support it from the box. And what's interesing - it's easy to add pictures in this format to Photos library and it will appear on all your devices that uses iCloud. But if you want to export this picture from Photos library - it will be converted to JPG on the fly, so it looks like you can't export original HEIC file.

The converter is free and open source (but it's for macOS only):

comment comments

Анимация касания индикатора в UISlider

Стояла задача - при касании слайдера анимировать в приложении сделать анимированное увеличение ползунка. Так же, как это сделано у Apple в приложениях Apple Music и Podcasts в плеере, когда начинаешь перематывать позицию воспроизведения. Пока искал способ сдандартными средствами, убил немало времени. Очень не хотелось писать прям свой кастомный слайдер, хотелось использовать системный UISlider, что мне, в итоге, и удалось.

Читать далее...

comment comments

SMS Антикредит

Надоел мне СМС-спам, который мне периодически приходит - то кредит предлагают, то ипотеку. Как раз, просматривая один из видосов с WWDC, увидел, что Apple дали API для фильтрации SMS-сообщений. Если сработает твой фильтр - то такие сообщения будут приходить без звукового или вибросигнала, втихую, и попадать в отдельную категорию спама в Сообщениях. 

Недолго думая, запили такой вот фильтр и выложил в App Store. Надеюсь, кому ещё, кроме меня, пригодится.

comment comments