Onfido sandbox error 422 Unprocessable Entity Validation

I’m trying to create a check in Onfido sandbox environment and it’s working fine when I use curl or python code while I’m receiving error 422 when I do the same request using swift from iOS.
here is the code that is confirmed to work in python:

def identity_check(self, applicant_id: str) -> dict:
        return self._post(
            'applicants/{}/checks'.format(applicant_id),
            data={
                'type': 'express',
                'reports[][name]': 'identity',
                'reports[][variant]': 'kyc',
            }
        )

and this is the swift code that gives me error 422:

 func executeCheck() {
        let headers: HTTPHeaders = [
            "Authorization": "Token token=\(token)",
            "Accept": "application/json",
        ]
        let parameters: [String: Any] = [
            "type": "express",
            "reports[][name]": "identity",
            "reports[][variant]": "kyc"
        ]
        Alamofire.request(
            "https://api.onfido.com/v2/applicants/\(self.applicantId)/checks",
            method: .post,
            parameters: parameters,
            encoding: JSONEncoding.default,
            headers: headers).validate().responseJSON { (response: DataResponse<Any>) in
                guard response.error == nil else {
                    return
                }
                self.saveCompletedDocumentState()
        }
    }

UIButton with gradient border and rounded corners

What I am trying to get is the a custom UIButton that has a gradient border (just the border is gradient) and rounded corners. I almost got to where I wanted to be, but having issues with the corners.
Here is what I currently have:
enter image description here

Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()

    let gradient = CAGradientLayer()
    gradient.frame =  CGRect(origin: CGPoint.zero, size: self.myButton.frame.size)
    gradient.colors = [UIColor.blue.cgColor, UIColor.green.cgColor]
    gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
    gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    gradient.cornerRadius = 15

    let shape = CAShapeLayer()
    shape.lineWidth = 5
    shape.path = UIBezierPath(rect: self.myButton.bounds).cgPath
    shape.strokeColor = UIColor.black.cgColor
    shape.fillColor = UIColor.clear.cgColor
    shape.cornerRadius = 15
    gradient.mask = shape

    self.myButton.clipsToBounds = true
    self.myButton.layer.cornerRadius = 15
    self.myButton.layer.addSublayer(gradient)
}

So the question is how do I display corners with gradient?

Creating UICollectionView which can scroll horizontally and vertically with Swift

I’m trying to create an UICollectionView which can scroll horizontally and vertically.

Here are my codes:

Here is the Model:

import UIKit

class AppCategory: NSObject {
    var name: String?
    var apps: [App]?

    static func sampleAppCategories() -> [AppCategory] {

        // Chapter 1
        let chapter1 = AppCategory()
        chapter1.name = NSLocalizedString("CHAPTER 1: ", comment: "1") + NSLocalizedString("19 Sections", comment: "title")

        var apps1 = [App]()

        let chapter1App = App()
        chapter1App.imageName = "IMG_2487"

        let chapter11App = App()
        chapter11App.imageName = "IMG_2502"

        let chapter12App = App()
        chapter12App.imageName = "IMG_2507"

        apps1.append(chapter1App)
        apps1.append(chapter11App)
         apps1.append(chapter12App)

        chapter1.apps = apps1

      // Chapter 2

        let chapter2 = AppCategory()
        chapter2.name = NSLocalizedString("CHAPTER 2: ", comment: "2") + NSLocalizedString("19 Sections", comment: "title")

        var apps2 = [App]()

        let chapter2App = App()
        chapter2App.imageName = "IMG_2508"


        apps2.append(chapter2App)

        chapter2.apps = apps2

        // Chapter 3

        let chapter3 = AppCategory()
        chapter3.name = NSLocalizedString("CHAPTER 3: ", comment: "title") + NSLocalizedString("19 Sections", comment: "title")


        var apps3 = [App]()

        let chapter3App = App()
        chapter3App.imageName = "IMG_2510"

        apps3.append(chapter3App)

        chapter3.apps = apps3

        // Chapter 4

        let chapter4 = AppCategory()
        chapter4.name = NSLocalizedString("CHAPTER 4: ", comment: "title") + NSLocalizedString("19 Sections", comment: "title")

        var apps4 = [App]()

        let chapter4App = App()
        chapter4App.imageName = "IMG_2511"

        apps4.append(chapter4App)

        chapter4.apps = apps4


        return [chapter1, chapter2, chapter3, chapter4]
    }

}


class App: NSObject {
    var imageName: String?
}

Here is the FeatureViewController:

import UIKit

class FeaturedViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {



    var appCategories: [AppCategory]?

    let verticalCellId = "verticalCellId"
    let horizontalCellId = "horizontalCellId"

    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = .white

        appCategories = AppCategory.sampleAppCategories()

        navigationItem.title = NSLocalizedString("Original", comment: "Original")
        navigationController?.navigationBar.prefersLargeTitles = true

         collectionView?.register(FeaturedVerticalCell.self, forCellWithReuseIdentifier: verticalCellId)


    }




    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let count = appCategories?.count {
            return count
        }
        return 0
    }

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: verticalCellId, for: indexPath) as! FeaturedVerticalCell
        cell.appCategory = appCategories?[indexPath.item]
        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0
    }





    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


        switch UIDevice.current.userInterfaceIdiom {
        case .phone:
            collectionView.reloadData()
            return CGSize(width:view.frame.width, height: view.frame.width / 5 * 4 )
        case .pad:
            let padding: CGFloat =  50
            let collectionViewSize = collectionView.frame.size.width - padding
            collectionView.reloadData()
            return CGSize(width: collectionViewSize / 5 * 4, height: collectionViewSize / 5 * 3 )
        case .tv:
            break
        case .carPlay:
            break
        case .unspecified:
            break

        }
        return CGSize(width: 0, height: 0)

    }

}

Here is the FeaturedVerticalCell:

import UIKit


struct Titles {
    var title: String?
    var images:[String]
}


class FeaturedVerticalCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {

    let horizontalCellId = "horizontalCellId"


    var appCategory: AppCategory? {
        didSet {
            if let name = appCategory?.name {
                titleLabel.text = name
            }
        }
    }



    let horizontalCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = UIColor.clear
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        return collectionView
    }()




    let titleLabel: UILabel = {
        let label = UILabel()
        label.translatesAutoresizingMaskIntoConstraints = false
        if UIDevice.current.userInterfaceIdiom == .phone {
            label.font = UIFont.systemFont(ofSize: 14.0, weight: UIFont.Weight.medium)
        } else {
            label.font = UIFont.systemFont(ofSize: 20.0, weight: UIFont.Weight.medium)
        }
        label.textAlignment = .left
        label.textColor = UIColor.darkGray
        return label
    }()



    override init(frame: CGRect) {
        super.init(frame: frame)

        horizontalCollectionView.dataSource = self
        horizontalCollectionView.delegate = self
        horizontalCollectionView.register(HorizontalCollectionViewCell.self, forCellWithReuseIdentifier: horizontalCellId)


        addSubview(horizontalCollectionView)
        horizontalCollectionView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 24).isActive = true
        horizontalCollectionView.topAnchor.constraint(equalTo: self.topAnchor, constant: 36).isActive = true
        horizontalCollectionView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -24).isActive = true
        horizontalCollectionView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 8).isActive = true



        addSubview(titleLabel)
        titleLabel.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 24).isActive = true
        titleLabel.rightAnchor.constraint(equalTo: self.rightAnchor, constant: -24).isActive = true
        titleLabel.bottomAnchor.constraint(equalTo: horizontalCollectionView.topAnchor, constant: 0).isActive = true
        titleLabel.topAnchor.constraint(equalTo: self.topAnchor, constant: 24).isActive = true





    }


    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }



  func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let count = appCategory?.apps?.count {
            return count
        }

        return 0

    }




    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell =  collectionView.dequeueReusableCell(withReuseIdentifier: horizontalCellId, for: indexPath) as! HorizontalCollectionViewCell
        cell.app = appCategory?.apps?[indexPath.item]
        return cell


    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: frame.height * 4 / 5, height: frame.height * 4 / 5)
    }



}




class HorizontalCollectionViewCell: UICollectionViewCell {

    var app: App? {
        didSet {
            if let imageName = app?.imageName {
                photoImageView.image = UIImage(named: imageName)
            }
        }
    }

    let photoImageView: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .scaleAspectFill
        iv.clipsToBounds = true
        iv.layer.cornerRadius = 10
        iv.image = #imageLiteral(resourceName: "IMG_2545")
        iv.layer.masksToBounds = true
        iv.translatesAutoresizingMaskIntoConstraints = false
        return iv
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)

        addSubview(photoImageView)
        photoImageView.leftAnchor.constraint(equalTo: self.leftAnchor, constant: 0).isActive = true
        photoImageView.rightAnchor.constraint(equalTo: self.rightAnchor, constant: 0).isActive = true
        photoImageView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: 0).isActive = true
        photoImageView.topAnchor.constraint(equalTo: self.topAnchor, constant: 0).isActive = true

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


}

But now I got a problem: the rows in horizontal sections will change somehow when I scroll vertically. Any way to get it back to work normally?

enter image description here

Calculating percentage between 2 Swift Date objects

I have an app with a timer that shows percentage between the creation date of a reminder to the end date.

I have 2 parameters (for example):

creationDate : 2018-02-16 17:06:10 UTC
‘endDate’ : 2018-02-16 15:07:09 UTC

The timer should show how much percent has passed between the 2 Dates.

I’ve tried:

let duration = self.creationDate.timeIntervalSince(self.endDate)
let timePassed = self.creationDate.timeIntervalSinceNow
let percent = (timePassed * 100) / duration

but the information I got was incorrect.

Does anybody know what’s wrong with my algorithm? Thanks!

Get an element that contains another element with a static text in iOS UITesting

How to build a query to get an element that contains another element by static text.

Example: Get the first table cell that contains a label with text “cool cell”

I need it because I have different cells and I want to get a cell that contains a specific text. Note that I’m interested to get the cell because I need to make sure that the cell contains another elements. The goal is to make sure that the cell with the title “I’m a cell” has also a label with text “cool”

Merge data locally & offline in iOS app with RealmSwift?

I’ve searched all over the internet for a tutorial on how to merge data in Realm DB! but actually I found nothing useful, Indeed no-one created a guide or tutorial on this topic.

I want to persist a book app contents locally in app but all the tutorials are on how to save the user “new data” in app and not about persisting and merging data in app such as a book app that have many chapters and includes long text materials that the user just want to read the contents(data) . .

I found out with Realm browser you can just edit the simulator’s data and it seems there’s no way to merge a Realm DB file with your app and finally publish it in App Store!

On the other hand I’m looking for a way to import long text data and some images to Realm and merge it with my app, so when user download the app, the user be able to see data in offline mode.

Thank you all for the time you’re spending on this

Simple URLSession example always fails with error

My macOS App is using a simple function wich should establish a connection to a Server but I can’t get it working, no matter what I try.

I copied an example from an other website but it does not work. I also watched other examples but most of them are very old and outdated.
Here is my code:

func connect(){

        // Set up the URL request
        let todoEndpoint: String = "https://www.google.com"
        guard let url = URL(string: todoEndpoint) else {
            print("Error: cannot create URL")
            return
        }
        let urlRequest = URLRequest(url: url)

        // set up the session
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)

        // make the request
        let task = session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
            // do stuff with response, data & error here
            print(error as Any)
            print(response as Any)
        })
        task.resume()

    }

I get the following error

dnssd_clientstub ConnectToServer: connect() failed path:/var/run/mDNSResponder Socket:11 Err:-1 Errno:1 Operation not permitted
2018-02-16 15:02:19.437098+0100 [4869:445869] [] nw_resolver_create_dns_service_locked DNSServiceCreateDelegateConnection failed: ServiceNotRunning(-65563)
2018-02-16 15:02:19.437839+0100 [4869:445869] TIC TCP Conn Failed [1:0x604000166d80]: 10:-72000 Err(-65563)
2018-02-16 15:02:19.451077+0100 [4869:445860] Task <29B127C0-8865-4AF4-8960-C1F892824A3C>.<1> HTTP load failed (error code: -1003 [10:-72000])
2018-02-16 15:02:19.451289+0100 [4869:445860] Task <29B127C0-8865-4AF4-8960-C1F892824A3C>.<1> finished with error - code: -1003
Optional(Error Domain=NSURLErrorDomain Code=-1003 "Es wurde kein Server mit dem angegebenen Hostnamen gefunden." UserInfo={NSUnderlyingError=0x60400024be80 {Error Domain=kCFErrorDomainCFNetwork Code=-1003 "(null)" UserInfo={_kCFStreamErrorCodeKey=-72000, _kCFStreamErrorDomainKey=10}}, NSErrorFailingURLStringKey=https://www.google.com/, NSErrorFailingURLKey=https://www.google.com/, _kCFStreamErrorDomainKey=10, _kCFStreamErrorCodeKey=-72000, NSLocalizedDescription=Es wurde kein Server mit dem angegebenen Hostnamen gefunden.})

What I am doing wrong. The localized description says: The host can not be found but its obviously thats not true. Any help I highly appreciated.

How to set line between points, if these points connected

I want to create a game similar to One Draw Line. I can not do it so that I can connect only those points that are already connected. I get it so that I can connect any point, regardless of whether they are connected or not. How to make it work properly?
LineCs are the lines that are already connected when starting. They are gray color. How to find out if there are linedots between 2 points?

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var drawingPlace: UIImageView!
    @IBOutlet weak var linePlaces: UIImageView!

    @IBOutlet weak var firstView: UIView!
    @IBOutlet weak var secondView: UIView!
    @IBOutlet weak var thirdView: UIView!
    @IBOutlet weak var fourthView: UIView!
    @IBOutlet weak var fiveView: UIView!

    var startTouch : CGPoint?
    var secondTouch : CGPoint?

    var currentContext : CGContext?
    var prevImage : UIImage?
    var setImage : UIImage?

    var hitView : UIView!

    var dot1 : CGPoint?
    var dot2 : CGPoint?
    var dot3 : CGPoint?
    var dot4 : CGPoint?
    var dot5 : CGPoint?
    var dot6 : CGPoint?

    let lineDots = UIBezierPath()

    override func viewDidLoad() {
        firstView.layer.cornerRadius = firstView.frame.height / 2
        secondView.layer.cornerRadius = secondView.frame.height / 2
        thirdView.layer.cornerRadius = thirdView.frame.height / 2
        fourthView.layer.cornerRadius = fourthView.frame.height / 2
        fiveView.layer.cornerRadius = fiveView.frame.height / 2
    }

    override func viewDidAppear(_ animated: Bool) {
        UIGraphicsBeginImageContext(self.view.frame.size)
        self.currentContext = UIGraphicsGetCurrentContext()
        self.setImage?.draw(in: self.view.bounds)

        lineDots.move(to: firstView!.center)
        lineDots.addLine(to: (secondView?.center)!)
        lineDots.move(to: firstView!.center)
        lineDots.addLine(to: (thirdView?.center)!)
        lineDots.move(to: secondView!.center)
        lineDots.addLine(to: (thirdView?.center)!)
        lineDots.move(to: thirdView!.center)
        lineDots.addLine(to: (fourthView?.center)!)
        lineDots.move(to: fourthView!.center)
        lineDots.addLine(to: (fiveView?.center)!)
        lineDots.move(to: fiveView!.center)
        lineDots.addLine(to: (thirdView?.center)!)
        lineDots.move(to: fiveView!.center)
        lineDots.addLine(to: (secondView?.center)!)
        lineDots.move(to: fourthView!.center)
        lineDots.addLine(to: (secondView?.center)!)

        lineDots.close()

        UIColor.init(red: 0.8, green: 0.8, blue: 0.8, alpha: 0.3).set()
        self.currentContext?.setLineWidth(3)
        self.currentContext?.addPath(lineDots.cgPath)
        self.currentContext?.strokePath()
        let img3 = self.currentContext?.makeImage()
        linePlaces.image = UIImage.init(cgImage: img3!)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        startTouch = touch!.location(in: self.view)
        hitView = self.view.hitTest(startTouch!, with: event)
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        for touch in touches {
            if hitView != self.view {
                secondTouch = touch.location(in: self.view)
                if (self.currentContext == nil) {
                    UIGraphicsBeginImageContext(self.view.frame.size)
                    self.currentContext = UIGraphicsGetCurrentContext()
                } else {
                    self.currentContext?.clear(CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
                }

                self.prevImage?.draw(in: self.view.bounds)

                let bezier = UIBezierPath()

                bezier.move(to: hitView.center)
                startTouch = touch.location(in: self.view)

                let moveView = self.view.hitTest(secondTouch!, with: event)

                if moveView != self.view {
                    bezier.addLine(to: secondTouch!)
                    bezier.addLine(to: moveView!.center)
                    hitView = self.view.hitTest(startTouch!, with: event)            
                    self.prevImage = self.drawingPlace.image
                } else {
                    bezier.addLine(to: secondTouch!)
                }

                bezier.close()

                UIColor.blue.set()
                UIColor.init(red: 0.3, green: 0.3, blue: 0.3, alpha: 1).set()
                self.currentContext?.setLineWidth(3)
                self.currentContext?.addPath(bezier.cgPath)
                self.currentContext?.strokePath()
                let img2 = self.currentContext?.makeImage()
                drawingPlace.image = UIImage.init(cgImage: img2!)
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        let endTouch = touch!.location(in: self.view)
        let endView = self.view.hitTest(endTouch, with: event)

        if endView != self.view {
            self.currentContext = nil
            self.prevImage = self.drawingPlace.image
        } else {
            self.drawingPlace.image = self.prevImage
        }
    }
}

Timer selector not firing but ONLY when called from delegate method

There once lived a class:

class Poo: UIViewController {

var timer = Timer()

func someFunctionInsideThisClass() {
    startTimer()
}

func startTimer() {
    print("Z216 - startTimer called!")
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(Poo.updateTimer)), userInfo: nil, repeats: true)
}

@objc private func updateTimer() {
    print("Z216 - updateTimer called!")
}

}

This class WORKED TOTALLY FINE — the timer worked properly and BOTH print functions verified that.

However, an evil Prince added an additional class Moof that contained:

@objc protocol MoofDelegate: class {
    @objc optional func someOtherDelegateMethodIMadePriorThatWorksFine()
    @objc optional func startTimer()
}

class Moof : NSObject {

weak var delegate: MoofDelegate?

var syncQueue: DispatchQueue? = nil

override init() {
    super.init()
    syncQueue = DispatchQueue(label: "CanUExplainZAT")
    self.syncQueue!.sync() {
        print("Z216 - we are calling startTimer from Moof!")
        self.delegate!.startTimer!()
    }
} 
}

…and he also changed the Poo class to:

class Poo: UIViewController, MoofDelegate {

var timer = Timer()

private var moof: Moof! = Moof()

override func viewDidLoad() {
    super.viewDidLoad()

    moof.delegate = self
}

@objc func startTimer() {
    print("Z216 - startTimer called!")
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(Poo.updateTimer)), userInfo: nil, repeats: true)
}

@objc private func updateTimer() {
    print("Z216 - updateTimer called!")
}

}

So now, instead of calling startTimer() from inside the Poo class, it’s being called from in the Moof class!

So, using this new delegate pattern, the print function inside startTimer() proves that startTimer() IS being called successfully, but… the wierd thing is… while it was working fine before, now the updateTimer() method is NOT subsequently called!

UPDATE:

I don’t really know why, but it works if I do this:

@objc func startTimer() {

    DispatchQueue.main.async(execute: {() -> Void in
        print("Z216 - startTimer called!")
        self.timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: (#selector(ViewController.updateTimer)), userInfo: nil, repeats: true)
    })
}

So, the theoretical question remains:

“Why would a timer instantiated inside a method, “method A” that works perfectly fine stop working (stop firing its own selector) only as a result of method A being changed to a delegate method (hint: It’s not because the method A is no longer being fired)… and then work again as a result of being enclosed in a DispatchQueue.main.async(execute: {() thingy.”

Can you explain that?