From 0ac5f7453ab8a357c3eaca3fc4dd5f141baf3900 Mon Sep 17 00:00:00 2001 From: Emma Blink Date: Thu, 29 Jun 2017 18:35:08 +0300 Subject: [PATCH 1/3] Migrated to Swift 3 --- LawTracker.xcodeproj/project.pbxproj | 15 +- LawTracker/AppDelegate.swift | 10 +- .../AppIcon.appiconset/Contents.json | 20 ++ .../Contents.json | 1 + LawTracker/Sources/Client/LTClient.swift | 66 ++--- .../Sources/Client/LTClientExtensions.swift | 179 +++++++------ LawTracker/Sources/Client/LTReach.swift | 54 ++-- .../LTAttributedStringExtensions.swift | 8 +- .../Extensions/LTFontSizeExtensions.swift | 2 +- .../Extensions/LTNSDateExtensions.swift | 50 ++-- .../Sources/Extensions/LTNSObject.swift | 2 +- .../Extensions/LTStringHeightExtensions.swift | 16 +- .../Extensions/LTTableViewExtensions.swift | 4 +- .../Extensions/LTUILabelExtensions.swift | 2 +- .../LTUIViewControllerExtensions.swift | 22 +- .../Sources/Models/CoreDataStackManager.swift | 185 +++++++------ LawTracker/Sources/Models/LTArrayModel.swift | 16 +- LawTracker/Sources/Models/LTChangeModel.swift | 20 +- .../Sources/Models/LTChangesModel.swift | 10 +- .../Sources/Models/LTCommitteeModel.swift | 12 +- .../Sources/Models/LTConvocationModel.swift | 20 +- LawTracker/Sources/Models/LTEntityModel.swift | 28 +- .../Sources/Models/LTInitiatorModel.swift | 4 +- .../Sources/Models/LTInitiatorTypeModel.swift | 8 +- LawTracker/Sources/Models/LTLawModel.swift | 22 +- LawTracker/Sources/Models/LTPersonModel.swift | 8 +- .../Sources/Models/LTSectionModel.swift | 8 +- .../Sources/Models/VTSettingModel.swift | 20 +- .../LTSelectAllButton/LTSelectAllButton.swift | 2 +- .../LTSelectAllButtonView.swift | 8 +- .../LTSwitchButton/LTSwitchButton.swift | 10 +- .../LTSwitchButton/LTSwitchButtonView.swift | 16 +- .../LTFilterRootView.swift | 6 +- .../LTFilterTableViewCell.swift | 8 +- .../LTFilterViewController.swift | 80 +++--- .../LTPanGestureRacognizer.swift | 36 +-- .../LTHelpContentController.swift | 12 +- .../LTHelpController/LTHelpContentView.swift | 4 +- .../LTHelpController/LTHelpController.swift | 56 ++-- .../LTCellHeaderView.swift | 4 +- .../LTMainContentTableViewCell.swift | 8 +- .../LTMainContentViewController.swift | 134 +++++----- .../MenuViewController/LTMenuDelegate.swift | 2 +- .../LTMenuTableViewCell.swift | 4 +- .../LTMenuViewController.swift | 24 +- .../LTNewsFeedRootView.swift | 40 +-- .../LTNewsFeedViewController.swift | 244 +++++++++--------- .../LTSliderAnimator.swift | 97 ++++--- .../LTTransitionContext.swift | 104 ++++---- .../UI/OTMLoadingView/OTMLoadingView.swift | 24 +- .../Sources/UI/OTMLoadingView/OTMView.swift | 12 +- LawTrackerTests/LawTrackerTests.swift | 2 +- 52 files changed, 889 insertions(+), 860 deletions(-) diff --git a/LawTracker.xcodeproj/project.pbxproj b/LawTracker.xcodeproj/project.pbxproj index 25e5c3f..0d4eb3a 100644 --- a/LawTracker.xcodeproj/project.pbxproj +++ b/LawTracker.xcodeproj/project.pbxproj @@ -446,15 +446,17 @@ isa = PBXProject; attributes = { LastSwiftUpdateCheck = 0710; - LastUpgradeCheck = 0710; + LastUpgradeCheck = 0830; ORGANIZATIONNAME = VarvaraMironova; TargetAttributes = { C7A29E471C0C9EAD001B0EF5 = { CreatedOnToolsVersion = 7.1.1; DevelopmentTeam = Z4W46D7MK3; + LastSwiftMigration = 0830; }; C7A29E601C0C9EAD001B0EF5 = { CreatedOnToolsVersion = 7.1.1; + LastSwiftMigration = 0830; TestTargetID = C7A29E471C0C9EAD001B0EF5; }; }; @@ -618,8 +620,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -662,8 +666,10 @@ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; CLANG_WARN_INT_CONVERSION = YES; CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_SUSPICIOUS_MOVE = YES; CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; @@ -682,6 +688,7 @@ IPHONEOS_DEPLOYMENT_TARGET = 9.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; VALIDATE_PRODUCT = YES; }; name = Release; @@ -697,6 +704,8 @@ PRODUCT_BUNDLE_IDENTIFIER = vmironova.ZakonoproektIOS; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; @@ -712,6 +721,8 @@ PRODUCT_BUNDLE_IDENTIFIER = vmironova.ZakonoproektIOS; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE = ""; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; @@ -724,6 +735,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = org.chesno.LawTrackerTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/LawTracker.app/LawTracker"; }; name = Debug; @@ -736,6 +748,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = org.chesno.LawTrackerTests; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/LawTracker.app/LawTracker"; }; name = Release; diff --git a/LawTracker/AppDelegate.swift b/LawTracker/AppDelegate.swift index 974cc04..a96bca6 100644 --- a/LawTracker/AppDelegate.swift +++ b/LawTracker/AppDelegate.swift @@ -15,18 +15,18 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { //check, if it is a first launch -> show helpViewController, else -> newsFeedViewController let window = UIWindow() let settings = VTSettingModel() let storyboard = UIStoryboard(name: "Main", bundle: nil) - let newsFeedController = storyboard.instantiateViewControllerWithIdentifier("LTNewsFeedViewController") as! LTNewsFeedViewController - let helpViewController = storyboard.instantiateViewControllerWithIdentifier("LTHelpController") as! LTHelpController + let newsFeedController = storyboard.instantiateViewController(withIdentifier: "LTNewsFeedViewController") as! LTNewsFeedViewController + let helpViewController = storyboard.instantiateViewController(withIdentifier: "LTHelpController") as! LTHelpController let rootController = settings.firstLaunch != true ? helpViewController : newsFeedController let navigationController = UINavigationController(rootViewController: rootController) - navigationController.navigationBarHidden = true + navigationController.isNavigationBarHidden = true window.rootViewController = navigationController self.window = window @@ -34,7 +34,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { return true } - func applicationWillTerminate(application: UIApplication) { + func applicationWillTerminate(_ application: UIApplication) { CoreDataStackManager.sharedInstance().saveContext() } } diff --git a/LawTracker/Assets.xcassets/AppIcon.appiconset/Contents.json b/LawTracker/Assets.xcassets/AppIcon.appiconset/Contents.json index f42f1cf..f70077b 100644 --- a/LawTracker/Assets.xcassets/AppIcon.appiconset/Contents.json +++ b/LawTracker/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -1,5 +1,15 @@ { "images" : [ + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "20x20", + "scale" : "3x" + }, { "size" : "29x29", "idiom" : "iphone", @@ -36,6 +46,16 @@ "filename" : "180.png", "scale" : "3x" }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "20x20", + "scale" : "2x" + }, { "size" : "29x29", "idiom" : "ipad", diff --git a/LawTracker/Assets.xcassets/screenshot1_landscape.imageset/Contents.json b/LawTracker/Assets.xcassets/screenshot1_landscape.imageset/Contents.json index 5162cc9..b7cb488 100644 --- a/LawTracker/Assets.xcassets/screenshot1_landscape.imageset/Contents.json +++ b/LawTracker/Assets.xcassets/screenshot1_landscape.imageset/Contents.json @@ -22,6 +22,7 @@ }, { "idiom" : "ipad", + "filename" : "1-3 (1).png", "scale" : "2x" } ], diff --git a/LawTracker/Sources/Client/LTClient.swift b/LawTracker/Sources/Client/LTClient.swift index 563673b..2e12d70 100644 --- a/LawTracker/Sources/Client/LTClient.swift +++ b/LawTracker/Sources/Client/LTClient.swift @@ -9,8 +9,8 @@ import UIKit class LTClient: NSObject { - var session : NSURLSession - var downloadTask : NSURLSessionDataTask? + var session : URLSession + var downloadTask : URLSessionDataTask? var methodArguments = [ "api" : String(), @@ -29,10 +29,10 @@ class LTClient: NSObject { return nil }() - typealias CompletionHander = (result: AnyObject!, error: NSError?) -> Void + typealias CompletionHander = (_ result: AnyObject?, _ error: NSError?) -> Void override init() { - session = NSURLSession.sharedSession() + session = URLSession.shared super.init() } @@ -48,89 +48,89 @@ class LTClient: NSObject { } // MARK: - Helpers - class func errorForMessage(message: String) -> NSError { + class func errorForMessage(_ message: String) -> NSError { let userInfo = [NSLocalizedDescriptionKey : message] return NSError(domain: "Application Error", code: 1, userInfo: userInfo) } - class func parseJSONWithCompletionHandler(data: NSData, completionHandler: CompletionHander) { + class func parseJSONWithCompletionHandler(_ data: Data, completionHandler: CompletionHander) { var parsingError: NSError? = nil let parsedResult: AnyObject? do { - parsedResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) + parsedResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments) as AnyObject } catch let error as NSError { parsingError = error parsedResult = nil } if let error = parsingError { - completionHandler(result: nil, error: error) + completionHandler(nil, error) } else { - completionHandler(result: parsedResult, error: nil) + completionHandler(parsedResult, nil) } } // MARK: - All purpose tasks - func task(request: NSURLRequest, completionHandler: (result: NSData!, error: NSError?) -> Void) -> NSURLSessionDataTask + func task(_ request: URLRequest, completionHandler: @escaping (_ result: Data?, _ error: NSError?) -> Void) -> URLSessionDataTask { - let task = session.dataTaskWithRequest(request) {data, response, downloadError in + let task = session.dataTask(with: request, completionHandler: {data, response, downloadError in if let error = downloadError { - completionHandler(result: nil, error: error) + completionHandler(nil, error as NSError) } else { - completionHandler(result: data, error: nil) + completionHandler(data, nil) } - } + }) task.resume() return task } - func taskWithURL(url: NSURL, completionHandler: (result: NSData!, error: NSError?) -> Void) -> NSURLSessionDataTask + func taskWithURL(_ url: URL, completionHandler: @escaping (_ result: Data?, _ error: NSError?) -> Void) -> URLSessionDataTask { - let task = session.dataTaskWithURL(url) {data, response, downloadError in + let task = session.dataTask(with: url, completionHandler: {data, response, downloadError in if let error = downloadError { - completionHandler(result: nil, error: error) + completionHandler(nil, error as NSError) } else { - completionHandler(result: data, error: nil) + completionHandler(data, nil) } - } + }) task.resume() return task } - func requestWithParameters(params: [String], completionHandler: (result: NSURLRequest?, error: NSError?) -> Void) { + func requestWithParameters(_ params: [String], completionHandler: (_ result: URLRequest?, _ error: NSError?) -> Void) { urlWithParameters(params) { (result, error) in - if let url = result as NSURL! { - if let request = NSMutableURLRequest(URL: url) as NSMutableURLRequest! { - request.HTTPMethod = "GET" - completionHandler(result: request, error: nil) + if let url = result as URL! { + if let request = NSMutableURLRequest(url: url) as NSMutableURLRequest! { + request.httpMethod = "GET" + completionHandler(request as URLRequest, nil) } else { let requestError = LTClient.errorForMessage(LTClient.KLTMessages.nsRequestError + "\(url.absoluteString)") - completionHandler(result: nil, error: requestError) + completionHandler(nil, requestError) } } else if let error = error as NSError! { - completionHandler(result: nil, error: error) + completionHandler(nil, error) } } } - func urlWithParameters(params: [String], completionHandler: (result: NSURL?, error: NSError?) -> Void) { - let urlString = params.joinWithSeparator("/") + "/" - if let unescapedURLString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) { - if let url = NSURL(string: unescapedURLString) as NSURL! { - completionHandler(result: url, error: nil) + func urlWithParameters(_ params: [String], completionHandler: (_ result: URL?, _ error: NSError?) -> Void) { + let urlString = params.joined(separator: "/") + "/" + if let unescapedURLString = urlString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) { + if let url = URL(string: unescapedURLString) as URL! { + completionHandler(url, nil) } else { let requestError = LTClient.errorForMessage(LTClient.KLTMessages.nsURLError + "\( urlString)") - completionHandler(result: nil, error: requestError) + completionHandler(nil, requestError) } } else { let requestError = LTClient.errorForMessage(LTClient.KLTMessages.nsURLError + "\( urlString)") - completionHandler(result: nil, error: requestError) + completionHandler(nil, requestError) } } } diff --git a/LawTracker/Sources/Client/LTClientExtensions.swift b/LawTracker/Sources/Client/LTClientExtensions.swift index 274c726..771231f 100644 --- a/LawTracker/Sources/Client/LTClientExtensions.swift +++ b/LawTracker/Sources/Client/LTClientExtensions.swift @@ -9,29 +9,29 @@ import Foundation extension LTClient { - func downloadConvocations(completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadConvocations(_ completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/council//convocation/api/ let urlVars = [kVTParameters.baseURL, kLTAPINames.council, kVTParameters.radaID, kLTMethodNames.convocation, kVTParameters.extras] requestWithParameters(urlVars) { [unowned self] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {(result, error) in + LTClient.parseJSONWithCompletionHandler(data!) {(result, error) in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let convocationsDictionary = result as? [[String: AnyObject]] { CoreDataStackManager.sharedInstance().storeConvocations(convocationsDictionary){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } @@ -41,175 +41,175 @@ extension LTClient { } } - func downloadLaws(completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadLaws(_ completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation//bill/api/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download initiators. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, currentConvocation!.id, kLTMethodNames.bill, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self, weak currentConvocation = currentConvocation!] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {(result, error) in + LTClient.parseJSONWithCompletionHandler(data!) {(result, error) in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let lawsDictionary = result as? [[String: AnyObject]] { CoreDataStackManager.sharedInstance().storeLaws(lawsDictionary, convocation: currentConvocation!.id){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func downloadCommittees(completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadCommittees(_ completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation//committees/api/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download committees. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, currentConvocation!.id, kLTMethodNames.committees, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self, weak currentConvocation = currentConvocation!] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {(result, error) in + LTClient.parseJSONWithCompletionHandler(data!) {(result, error) in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let committees = result as? [[String: AnyObject]] { CoreDataStackManager.sharedInstance().storeCommittees(committees, convocation: currentConvocation!.id){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func downloadPersons(completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadPersons(_ completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/persons/json/deputies/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download initiators. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } let urlVars = [kVTParameters.baseURL, kLTAPINames.persons, kVTParameters.format, kLTMethodNames.deputies, currentConvocation!.number] requestWithParameters(urlVars) {[unowned self] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {result, error in + LTClient.parseJSONWithCompletionHandler(data!) {result, error in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let persons = result as? [[String: AnyObject]] { CoreDataStackManager.sharedInstance().storePersons(persons){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func downloadInitiatorTypes(completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadInitiatorTypes(_ completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation/initiator-types/api/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download initiators. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, kLTMethodNames.initiatorTypes, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {result, error in + LTClient.parseJSONWithCompletionHandler(data!) {result, error in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let types = result as? [String: AnyObject] { CoreDataStackManager.sharedInstance().storeInitiatorTypes(types){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func downloadChanges(date:NSDate, completionHandler:(success: Bool, error: NSError?) -> Void) { + func downloadChanges(_ date:Date, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation//bill-statuses//api/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download status changes. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } @@ -217,130 +217,125 @@ extension LTClient { let dateString = date.string("yyyy-MM-dd") let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, currentConvocation!.id, kLTMethodNames.billStatuses, dateString, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {result, error in + LTClient.parseJSONWithCompletionHandler(data!) {result, error in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let changes = result as? [[String: AnyObject]] { CoreDataStackManager.sharedInstance().storeChanges(date, changes: changes){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func getLawWithId(id: String, completionHandler:(success: Bool, error: NSError?) -> Void) { + func getLawWithId(_ id: String, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation//bill/<номер законопроекту>/api/ if nil == currentConvocation { let contentError = LTClient.errorForMessage("Cannot download bills. " + LTClient.KLTMessages.noCurrentConvocation) - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) return } let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, currentConvocation!.id, kLTMethodNames.bill, id, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self, weak currentConvocation = currentConvocation!] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {result, error in + LTClient.parseJSONWithCompletionHandler(data!) {result, error in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if var lawDictionary = result as? [String: AnyObject] { - lawDictionary["number"] = id - var lawArray = [NSDictionary]() - lawArray.append(lawDictionary) - - CoreDataStackManager.sharedInstance().storeLaws(lawArray, convocation: currentConvocation!.id){finished in + lawDictionary["number"] = id as AnyObject + CoreDataStackManager.sharedInstance().storeLaws([lawDictionary], convocation: currentConvocation!.id){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func getInitiatorWithId(id: String, completionHandler:(success: Bool, error: NSError?) -> Void) { + func getInitiatorWithId(_ id: String, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { //http://www.chesno.org/legislation/initiators//api/ let urlVars = [kVTParameters.baseURL, kLTAPINames.legislation, kLTMethodNames.initiators, id, kVTParameters.extras] requestWithParameters(urlVars) {[unowned self] (result, error) -> Void in - if let request = result as NSURLRequest! { + if let request = result as URLRequest! { self.downloadTask = self.task(request){data, error in - if nil != error { - completionHandler(success: false, error: error) + if nil == data { + completionHandler(false, error) } else { - LTClient.parseJSONWithCompletionHandler(data) {result, error in + LTClient.parseJSONWithCompletionHandler(data!) {result, error in if nil != error { - completionHandler(success: false, error: error) + completionHandler(false, error) } else { if let person = result as? [String: AnyObject] { - var personArray = [NSDictionary]() - personArray.append(person) - CoreDataStackManager.sharedInstance().storePersons(personArray){finished in + CoreDataStackManager.sharedInstance().storePersons([person]){finished in if finished { - completionHandler(success: true, error: nil) + completionHandler(true, nil) } } } else { let contentError = LTClient.errorForMessage(LTClient.KLTMessages.parseJSONError + "\(result)") - completionHandler(success: false, error: contentError) + completionHandler(false, contentError) } } } } } } else { - completionHandler(success: false, error: error) + completionHandler(false, error) } } } - func getCommitteeWithId(id: String, completionHandler:(success: Bool, error: NSError?) -> Void) { + func getCommitteeWithId(_ id: String, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { downloadCommittees { (success, error) -> Void in if success { - completionHandler(success: success, error: nil) + completionHandler(success, nil) } else { - completionHandler(success: success, error: error) + completionHandler(success, error) } } } - func getInitiatorTypeWithId(id: String, completionHandler:(success: Bool, error: NSError?) -> Void) { + func getInitiatorTypeWithId(_ id: String, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { downloadInitiatorTypes { (success, error) -> Void in if success { - completionHandler(success: success, error: nil) + completionHandler(success, nil) } else { - completionHandler(success: success, error: error) + completionHandler(success, error) } } } @@ -351,4 +346,4 @@ extension LTClient { } } -} \ No newline at end of file +} diff --git a/LawTracker/Sources/Client/LTReach.swift b/LawTracker/Sources/Client/LTReach.swift index bb85d09..e6e9094 100644 --- a/LawTracker/Sources/Client/LTReach.swift +++ b/LawTracker/Sources/Client/LTReach.swift @@ -38,47 +38,49 @@ import SystemConfiguration let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification" enum ReachabilityType: CustomStringConvertible { - case WWAN - case WiFi + case wwan + case wiFi var description: String { switch self { - case .WWAN: return "WWAN" - case .WiFi: return "WiFi" + case .wwan: return "WWAN" + case .wiFi: return "WiFi" } } } enum ReachabilityStatus: CustomStringConvertible { - case Offline - case Online(ReachabilityType) - case Unknown + case offline + case online(ReachabilityType) + case unknown var description: String { switch self { - case .Offline: return "Offline" - case .Online(let type): return "Online (\(type))" - case .Unknown: return "Unknown" + case .offline: return "Offline" + case .online(let type): return "Online (\(type))" + case .unknown: return "Unknown" } } } -public class Reach { +open class Reach { func connectionStatus() -> ReachabilityStatus { var zeroAddress = sockaddr_in() - zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) + zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) - guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, { - SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) + guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in + SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) + } }) else { - return .Unknown + return .unknown } var flags : SCNetworkReachabilityFlags = [] if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) { - return .Unknown + return .unknown } return ReachabilityStatus(reachabilityFlags: flags) @@ -93,31 +95,31 @@ public class Reach { SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in let status = ReachabilityStatus(reachabilityFlags: flags) - NSNotificationCenter.defaultCenter().postNotificationName(ReachabilityStatusChangedNotification, + NotificationCenter.default.post(name: Notification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description]) }, &context) - SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes) + SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) } } extension ReachabilityStatus { - private init(reachabilityFlags flags: SCNetworkReachabilityFlags) { - let connectionRequired = flags.contains(.ConnectionRequired) - let isReachable = flags.contains(.Reachable) - let isWWAN = flags.contains(.IsWWAN) + fileprivate init(reachabilityFlags flags: SCNetworkReachabilityFlags) { + let connectionRequired = flags.contains(.connectionRequired) + let isReachable = flags.contains(.reachable) + let isWWAN = flags.contains(.isWWAN) if !connectionRequired && isReachable { if isWWAN { - self = .Online(.WWAN) + self = .online(.wwan) } else { - self = .Online(.WiFi) + self = .online(.wiFi) } } else { - self = .Offline + self = .offline } } -} \ No newline at end of file +} diff --git a/LawTracker/Sources/Extensions/LTAttributedStringExtensions.swift b/LawTracker/Sources/Extensions/LTAttributedStringExtensions.swift index f2af8c7..f8a2651 100644 --- a/LawTracker/Sources/Extensions/LTAttributedStringExtensions.swift +++ b/LawTracker/Sources/Extensions/LTAttributedStringExtensions.swift @@ -8,18 +8,18 @@ import Foundation -extension SequenceType where Generator.Element: NSAttributedString { - func joinWithSeparator(separator: NSAttributedString) -> NSAttributedString { +extension Sequence where Iterator.Element: NSAttributedString { + func joinWithSeparator(_ separator: NSAttributedString) -> NSAttributedString { var isFirst = true return self.reduce(NSMutableAttributedString()) { (result, item) in if isFirst { isFirst = false } else { - result.appendAttributedString(separator) + result.append(separator) } - result.appendAttributedString(item) + result.append(item) return result } diff --git a/LawTracker/Sources/Extensions/LTFontSizeExtensions.swift b/LawTracker/Sources/Extensions/LTFontSizeExtensions.swift index 04a7148..13f6e67 100644 --- a/LawTracker/Sources/Extensions/LTFontSizeExtensions.swift +++ b/LawTracker/Sources/Extensions/LTFontSizeExtensions.swift @@ -11,7 +11,7 @@ import UIKit extension UIFont { func screenProportionalFont() -> UIFont { - let widthProportionalSize = pointSize * CGRectGetWidth(UIScreen.mainScreen().bounds) / 414.0 + let widthProportionalSize = pointSize * UIScreen.main.bounds.width / 414.0 let fontSize = widthProportionalSize < pointSize ? widthProportionalSize : pointSize return UIFont(name: fontName, size: fontSize)! diff --git a/LawTracker/Sources/Extensions/LTNSDateExtensions.swift b/LawTracker/Sources/Extensions/LTNSDateExtensions.swift index a59f980..9dae121 100644 --- a/LawTracker/Sources/Extensions/LTNSDateExtensions.swift +++ b/LawTracker/Sources/Extensions/LTNSDateExtensions.swift @@ -8,14 +8,14 @@ import Foundation -extension NSDate { +extension Date { - func string(format: String) -> String { - let dateFormatter = NSDateFormatter() - dateFormatter.calendar = NSCalendar.currentCalendar() + func string(_ format: String) -> String { + let dateFormatter = DateFormatter() + dateFormatter.calendar = Calendar.current dateFormatter.dateFormat = format - if let result = dateFormatter.stringFromDate(self) as String! { + if let result = dateFormatter.string(from: self) as String! { return result } @@ -23,39 +23,37 @@ extension NSDate { } func longString() -> String { - let dateFormatter = NSDateFormatter() - dateFormatter.calendar = NSCalendar.currentCalendar() - dateFormatter.dateStyle = .LongStyle - dateFormatter.locale = NSLocale(localeIdentifier: "uk-Cyrl") + let dateFormatter = DateFormatter() + dateFormatter.calendar = Calendar.current + dateFormatter.dateStyle = .long + dateFormatter.locale = Locale(identifier: "uk-Cyrl") - if let result = dateFormatter.stringFromDate(self) as String! { + if let result = dateFormatter.string(from: self) as String! { return result } return "" } - func previousDay() -> NSDate { - let calendar = NSCalendar.currentCalendar() - let components = calendar.components([.Year, .Month, .Day], fromDate: self) - components.day -= 1 - - return calendar.dateFromComponents(components)! + func previousDay() -> Date { + let calendar = Calendar.current + var components = calendar.dateComponents([.year, .month, .day], from: self) + components.day = components.day! - 1 + return calendar.date(from: components)! } - func nextDay() -> NSDate { - let calendar = NSCalendar.currentCalendar() - let components = calendar.components([.Year, .Month, .Day], fromDate: self) - components.day += 1 - - return calendar.dateFromComponents(components)! + func nextDay() -> Date { + let calendar = Calendar.current + var components = calendar.dateComponents([.year, .month, .day], from: self) + components.day = components.day! + 1 + return calendar.date(from: components)! } - func dateWithoutTime() -> NSDate { - let calendar = NSCalendar.currentCalendar() - let components = calendar.components([.Year, .Month, .Day], fromDate: self) + func dateWithoutTime() -> Date { + let calendar = Calendar.current + let components = (calendar as NSCalendar).components([.year, .month, .day], from: self) - return calendar.dateFromComponents(components)! + return calendar.date(from: components)! } } diff --git a/LawTracker/Sources/Extensions/LTNSObject.swift b/LawTracker/Sources/Extensions/LTNSObject.swift index dc25066..28087fc 100644 --- a/LawTracker/Sources/Extensions/LTNSObject.swift +++ b/LawTracker/Sources/Extensions/LTNSObject.swift @@ -22,7 +22,7 @@ enum LTState : Int { extension NSObject { - func synchronized(lock: AnyObject, closure:() -> ()) { + func synchronized(_ lock: AnyObject, closure:() -> ()) { objc_sync_enter(lock) closure() objc_sync_exit(lock) diff --git a/LawTracker/Sources/Extensions/LTStringHeightExtensions.swift b/LawTracker/Sources/Extensions/LTStringHeightExtensions.swift index 2d38c3d..3ee8b62 100644 --- a/LawTracker/Sources/Extensions/LTStringHeightExtensions.swift +++ b/LawTracker/Sources/Extensions/LTStringHeightExtensions.swift @@ -10,18 +10,18 @@ import Foundation import UIKit extension String { - func getHeight(width: CGFloat, font: UIFont) -> CGFloat { - let constraintRect = CGSize(width: width, height: CGFloat.max) + func getHeight(_ width: CGFloat, font: UIFont) -> CGFloat { + let constraintRect = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude) - let boundingBox = self.boundingRectWithSize(constraintRect, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) + let boundingBox = self.boundingRect(with: constraintRect, options: NSStringDrawingOptions.usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil) return boundingBox.height } - func date() -> NSDate? { - let dateFormatter = NSDateFormatter() + func date() -> Date? { + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm" - if let date = dateFormatter.dateFromString(self) as NSDate! { + if let date = dateFormatter.date(from: self) as Date! { return date } @@ -50,11 +50,11 @@ extension String { func attributedLink() -> NSAttributedString? { if let font = UIFont(name: "Arial", size: 12.0) as UIFont! { - let attributes = [NSLinkAttributeName: self, NSFontAttributeName: font] + let attributes = [NSLinkAttributeName: self, NSFontAttributeName: font] as [String : Any] return NSMutableAttributedString(string:self, attributes:attributes) } return nil } -} \ No newline at end of file +} diff --git a/LawTracker/Sources/Extensions/LTTableViewExtensions.swift b/LawTracker/Sources/Extensions/LTTableViewExtensions.swift index 3d00480..88ff0dc 100644 --- a/LawTracker/Sources/Extensions/LTTableViewExtensions.swift +++ b/LawTracker/Sources/Extensions/LTTableViewExtensions.swift @@ -10,7 +10,7 @@ import UIKit extension UITableView { - func reusableCell(cellClass: AnyClass, indexPath: NSIndexPath) -> UITableViewCell { - return self.dequeueReusableCellWithIdentifier(String(cellClass), forIndexPath: indexPath) + func reusableCell(_ cellClass: AnyClass, indexPath: IndexPath) -> UITableViewCell { + return self.dequeueReusableCell(withIdentifier: String(describing: cellClass), for: indexPath) } } diff --git a/LawTracker/Sources/Extensions/LTUILabelExtensions.swift b/LawTracker/Sources/Extensions/LTUILabelExtensions.swift index 3e7849c..3bd721c 100644 --- a/LawTracker/Sources/Extensions/LTUILabelExtensions.swift +++ b/LawTracker/Sources/Extensions/LTUILabelExtensions.swift @@ -13,7 +13,7 @@ extension UILabel { func fit() { numberOfLines = 0 var rect = frame - let size = sizeThatFits(CGSizeMake(CGRectGetWidth(frame), 0)) + let size = sizeThatFits(CGSize(width: frame.width, height: 0)) rect.size.height = size.height frame = rect } diff --git a/LawTracker/Sources/Extensions/LTUIViewControllerExtensions.swift b/LawTracker/Sources/Extensions/LTUIViewControllerExtensions.swift index 4c9ccb6..78778ba 100644 --- a/LawTracker/Sources/Extensions/LTUIViewControllerExtensions.swift +++ b/LawTracker/Sources/Extensions/LTUIViewControllerExtensions.swift @@ -11,26 +11,26 @@ import UIKit extension UIViewController { - func addChildViewControllerInView(childController: UIViewController, view: UIView) { + func addChildViewControllerInView(_ childController: UIViewController, view: UIView) { childController.view.frame = view.bounds view.addSubview(childController.view) addChildViewController(childController) - childController.didMoveToParentViewController(self) + childController.didMove(toParentViewController: self) } - func removeChildController(childController: UIViewController) { - dispatch_async(dispatch_get_main_queue()) { - childController.willMoveToParentViewController(nil) + func removeChildController(_ childController: UIViewController) { + DispatchQueue.main.async { + childController.willMove(toParentViewController: nil) childController.view.removeFromSuperview() childController.removeFromParentViewController() } } - func displayError(error: NSError) { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in - let alertViewController: UIAlertController = UIAlertController(title: "", message: error.localizedDescription, preferredStyle: .Alert) - alertViewController.addAction(UIAlertAction(title: "Продовжити", style: .Default, handler: nil)) - self.presentViewController(alertViewController, animated: true, completion: nil) + func displayError(_ error: NSError) { + DispatchQueue.main.async {[unowned self] in + let alertViewController: UIAlertController = UIAlertController(title: "", message: error.localizedDescription, preferredStyle: .alert) + alertViewController.addAction(UIAlertAction(title: "Продовжити", style: .default, handler: nil)) + self.present(alertViewController, animated: true, completion: nil) } } -} \ No newline at end of file +} diff --git a/LawTracker/Sources/Models/CoreDataStackManager.swift b/LawTracker/Sources/Models/CoreDataStackManager.swift index 6eacc02..16d5623 100644 --- a/LawTracker/Sources/Models/CoreDataStackManager.swift +++ b/LawTracker/Sources/Models/CoreDataStackManager.swift @@ -14,54 +14,50 @@ private let kVTMomdFileName = "LawTracker" private let kLTQueueName = "CoreDataQueue" class CoreDataStackManager { - + // MARK: - Shared Instance class func sharedInstance() -> CoreDataStackManager { struct Static { - static let instance = CoreDataStackManager() + static let instance = { CoreDataStackManager() }() } return Static.instance } - class func coreDataQueue() -> dispatch_queue_t { + class func coreDataQueue() -> DispatchQueue { struct Static { - static var onceToken: dispatch_once_t = 0 - static var instance: dispatch_queue_t? = nil - } - - dispatch_once(&Static.onceToken) { - Static.instance = dispatch_queue_create(kLTQueueName, DISPATCH_QUEUE_SERIAL) + static var onceToken: Int = 0 + static var instance = { DispatchQueue(label: kLTQueueName, attributes: []) }() } - return Static.instance! + return Static.instance } // MARK: - The Core Data stack. The code has been moved, unaltered, from the AppDelegate. - lazy var applicationDocumentsDirectory: NSURL = { - let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) + lazy var applicationDocumentsDirectory: URL = { + let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { - let modelURL = NSBundle.mainBundle().URLForResource(kVTMomdFileName, withExtension: "momd")! - return NSManagedObjectModel(contentsOfURL: modelURL)! + let modelURL = Bundle.main.url(forResource: kVTMomdFileName, withExtension: "momd")! + return NSManagedObjectModel(contentsOf: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { let coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) - let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(kVTSQLFileName) + let url = self.applicationDocumentsDirectory.appendingPathComponent(kVTSQLFileName) - print("sqlite path: \(url.path!)") + print("sqlite path: \(url.path)") var failureReason = "There was an error creating or loading the application's saved data." do { - try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) + try coordinator!.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil) } catch { // Report any error we got. var dict = [String: AnyObject]() - dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" - dict[NSLocalizedFailureReasonErrorKey] = failureReason + dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject + dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject dict[NSUnderlyingErrorKey] = error as NSError let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) @@ -76,7 +72,7 @@ class CoreDataStackManager { lazy var managedObjectContext: NSManagedObjectContext = { let coordinator = self.persistentStoreCoordinator - var managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType) + var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType) managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext @@ -95,13 +91,13 @@ class CoreDataStackManager { } } - func delete(object:NSManagedObject) { - managedObjectContext.deleteObject(object) + func delete(_ object:NSManagedObject) { + managedObjectContext.delete(object) } - func storeConvocations(convocations: [NSDictionary], completionHandler: (finished: Bool) -> Void) { + func storeConvocations(_ convocations: [[String: AnyObject]], completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) { + queue.async { for convocationArray in convocations { var convocationID = String() if let id = convocationArray["id"] as? String { @@ -111,19 +107,19 @@ class CoreDataStackManager { } if nil == LTConvocationModel.modelWithID(convocationID, entityName: "LTConvocationModel") { - _ = LTConvocationModel(dictionary: convocationArray as! [String : AnyObject], context: self.managedObjectContext, entityName:"LTConvocationModel") + _ = LTConvocationModel(dictionary: convocationArray, context: self.managedObjectContext, entityName:"LTConvocationModel") } } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func storeLaws(laws: [NSDictionary], convocation: String, completionHandler: (finished: Bool) -> Void) { + func storeLaws(_ laws: [[String: AnyObject]], convocation: String, completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) { [unowned self, weak context = managedObjectContext] in + queue.async { [unowned self, weak context = managedObjectContext] in for lawArray in laws { var lawId = String() if let id = lawArray["id"] as? String { @@ -133,26 +129,25 @@ class CoreDataStackManager { } if nil == LTLawModel.modelWithID(lawId, entityName: "LTLawModel") { - if var mutableLawArray = lawArray as? [String : AnyObject] { - mutableLawArray["convocation"] = convocation - - //store initiators - self.storeInitiators(mutableLawArray) { (result, finished) in - if finished { - mutableLawArray["initiatorModels"] = result - - //storeCommittees - if let committeeID = mutableLawArray["committee"] as? Int { - let committeeIDString = "\(committeeID)" - if let committeeModel = LTCommitteeModel.modelWithID(committeeIDString, entityName:"LTCommitteeModel") as! LTCommitteeModel! { - mutableLawArray["committeeModel"] = committeeModel - } else { - LTClient.sharedInstance().getCommitteeWithId(committeeIDString){success, error in - if success { - dispatch_async(CoreDataStackManager.coreDataQueue()){ - if let committee = LTCommitteeModel.modelWithID(committeeIDString, entityName: "LTCommitteeModel") as? LTCommitteeModel! { - mutableLawArray["committeeModel"] = committee - } + var mutableLawArray = lawArray + mutableLawArray["convocation"] = convocation as AnyObject + + //store initiators + self.storeInitiators(mutableLawArray) { (result, finished) in + if finished { + mutableLawArray["initiatorModels"] = result as AnyObject + + //storeCommittees + if let committeeID = mutableLawArray["committee"] as? Int { + let committeeIDString = "\(committeeID)" + if let committeeModel = LTCommitteeModel.modelWithID(committeeIDString, entityName:"LTCommitteeModel") as! LTCommitteeModel! { + mutableLawArray["committeeModel"] = committeeModel + } else { + LTClient.sharedInstance().getCommitteeWithId(committeeIDString){success, error in + if success { + CoreDataStackManager.coreDataQueue().async{ + if let committee = LTCommitteeModel.modelWithID(committeeIDString, entityName: "LTCommitteeModel") as? LTCommitteeModel! { + mutableLawArray["committeeModel"] = committee } } } @@ -160,21 +155,21 @@ class CoreDataStackManager { } } } - - _ = LTLawModel(dictionary: mutableLawArray, context: context!, entityName:"LTLawModel") } + + _ = LTLawModel(dictionary: mutableLawArray, context: context!, entityName:"LTLawModel") } } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func storeCommittees(committees: [NSDictionary], convocation: String, completionHandler: (finished: Bool) -> Void) { + func storeCommittees(_ committees: [[String: AnyObject]], convocation: String, completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) {[unowned self, weak context = managedObjectContext] in + queue.async {[unowned self, weak context = managedObjectContext] in for committeeArray in committees { var committeeId = String() if let id = committeeArray["id"] as? String { @@ -184,51 +179,50 @@ class CoreDataStackManager { } if nil == LTCommitteeModel.modelWithID(committeeId, entityName: "LTCommitteeModel") { - if var mutableCommitteeArray = committeeArray as? [String : AnyObject] { - mutableCommitteeArray["convocation"] = convocation - _ = LTCommitteeModel(dictionary: mutableCommitteeArray, context: context!, entityName:"LTCommitteeModel") - } + var mutableCommitteeArray = committeeArray + mutableCommitteeArray["convocation"] = convocation as AnyObject + _ = LTCommitteeModel(dictionary: mutableCommitteeArray, context: context!, entityName:"LTCommitteeModel") } } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func storeInitiatorTypes(types: [String : AnyObject], completionHandler: (finished: Bool) -> Void) { + func storeInitiatorTypes(_ types: [String : AnyObject], completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) {[unowned self, weak context = managedObjectContext] in + queue.async {[unowned self, weak context = managedObjectContext] in for (key, value) in types { if nil == LTInitiatorTypeModel.modelWithID(key, entityName: "LTInitiatorTypeModel") { - let type = ["id": key, "title": value] - _ = LTInitiatorTypeModel(dictionary: type, context: context!, entityName:"LTInitiatorTypeModel") + let type = ["id": key, "title": value] as [String : Any] + _ = LTInitiatorTypeModel(dictionary: type as [String : AnyObject], context: context!, entityName:"LTInitiatorTypeModel") } } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func storePersons(persons: [NSDictionary], completionHandler: (finished: Bool) -> Void) { + func storePersons(_ persons: [[String: AnyObject]], completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) {[unowned self, weak context = managedObjectContext] in + queue.async {[unowned self, weak context = managedObjectContext] in for person in persons { - _ = LTPersonModel(dictionary: person as! [String : AnyObject], context: context!, entityName:"LTPersonModel") + _ = LTPersonModel(dictionary: person, context: context!, entityName:"LTPersonModel") } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func storeChanges(date: NSDate, changes: [NSDictionary], completionHandler: (finished: Bool) -> Void) { + func storeChanges(_ date: Date, changes: [[String: AnyObject]], completionHandler: @escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) {[unowned self, weak context = managedObjectContext] in + queue.async {[unowned self, weak context = managedObjectContext] in let dateString = date.string("yyyy-MM-dd") for changeArray in changes { var changeId = dateString @@ -239,17 +233,16 @@ class CoreDataStackManager { } if nil == LTChangeModel.modelWithID(changeId, entityName: "LTChangeModel") { - if var mutableChangeArray = changeArray as? [String : AnyObject] { - mutableChangeArray["date"] = date - mutableChangeArray["id"] = changeId - - //get lawModel - if let lawNumber = mutableChangeArray["bill"] as? String { - self.getLawWithNumber(lawNumber) { (result, finished) in - mutableChangeArray["billModel"] = result - dispatch_async(queue) { - _ = LTChangeModel(dictionary: mutableChangeArray, context: context!) - } + var mutableChangeArray = changeArray + mutableChangeArray["date"] = date as AnyObject + mutableChangeArray["id"] = changeId as AnyObject + + //get lawModel + if let lawNumber = mutableChangeArray["bill"] as? String { + self.getLawWithNumber(lawNumber) { (result, finished) in + mutableChangeArray["billModel"] = result + queue.async { + _ = LTChangeModel(dictionary: mutableChangeArray, context: context!) } } } @@ -257,36 +250,36 @@ class CoreDataStackManager { } self.saveContext() - completionHandler(finished: true) + completionHandler(true) } } - func clearEntity(entityName: String, completionHandler:(success: Bool, error: NSError?) -> Void) { + func clearEntity(_ entityName: String, completionHandler:@escaping (_ success: Bool, _ error: NSError?) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) {[unowned self, weak context = managedObjectContext] in - let fetchRequest = NSFetchRequest(entityName: entityName) + queue.async {[unowned self, weak context = managedObjectContext] in + let fetchRequest = NSFetchRequest(entityName: entityName) let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest) do { if let persistentStoreCoordinator = self.persistentStoreCoordinator as NSPersistentStoreCoordinator! { - try persistentStoreCoordinator.executeRequest(deleteRequest, withContext: context!) - completionHandler(success: true, error: nil) + try persistentStoreCoordinator.execute(deleteRequest, with: context!) + completionHandler(true, nil) } } catch let error as NSError { - completionHandler(success: true, error: error) + completionHandler(true, error) } } } - private func getLawWithNumber(lawNumber: String, completionHandler:(result: LTLawModel, finished: Bool) -> Void) { + fileprivate func getLawWithNumber(_ lawNumber: String, completionHandler:@escaping (_ result: LTLawModel, _ finished: Bool) -> Void) { if let lawModel = LTLawModel.lawWithNumber(lawNumber) as LTLawModel! { - completionHandler(result: lawModel, finished: true) + completionHandler(lawModel, true) } else { //there is no law with lawID so, make request to server LTClient.sharedInstance().getLawWithId(lawNumber) {success, error in if success { - dispatch_async(CoreDataStackManager.coreDataQueue()){ + CoreDataStackManager.coreDataQueue().async{ if let law = LTLawModel.lawWithNumber(lawNumber) as LTLawModel! { - completionHandler(result: law, finished: true) + completionHandler(law, true) } } } @@ -294,7 +287,7 @@ class CoreDataStackManager { } } - private func storeInitiators(array: [String : AnyObject], completionHandler:(result: [LTInitiatorModel], finished: Bool) -> Void) { + fileprivate func storeInitiators(_ array: [String : AnyObject], completionHandler:(_ result: [LTInitiatorModel], _ finished: Bool) -> Void) { var initiatorModels = [LTInitiatorModel]() let queue = CoreDataStackManager.coreDataQueue() if let typeID = array["initiator_type"] as? String { @@ -307,7 +300,7 @@ class CoreDataStackManager { } else { LTClient.sharedInstance().getInitiatorWithId(idString){success, error in if success { - dispatch_async(queue){ + queue.async{ if let initiator = LTInitiatorModel.modelWithID(idString, entityName: "LTInitiatorModel") as? LTInitiatorModel! { initiatorModels.append(initiator) } @@ -323,7 +316,7 @@ class CoreDataStackManager { } else { LTClient.sharedInstance().getInitiatorTypeWithId(typeID){success, error in if success { - dispatch_async(queue){ + queue.async{ if let initiatorModel = LTInitiatorModel.modelWithID(typeID, entityName: "LTInitiatorModel") as? LTInitiatorModel! { initiatorModels.append(initiatorModel) } @@ -334,10 +327,10 @@ class CoreDataStackManager { } } - completionHandler(result: initiatorModels, finished: true) + completionHandler(initiatorModels, true) } - func synchronized(lock: AnyObject, closure:() -> ()) { + func synchronized(_ lock: AnyObject, closure:() -> ()) { objc_sync_enter(lock) closure() objc_sync_exit(lock) diff --git a/LawTracker/Sources/Models/LTArrayModel.swift b/LawTracker/Sources/Models/LTArrayModel.swift index 9023d9e..8d79c45 100644 --- a/LawTracker/Sources/Models/LTArrayModel.swift +++ b/LawTracker/Sources/Models/LTArrayModel.swift @@ -12,15 +12,15 @@ import Foundation class LTArrayModel: NSObject, NSFetchedResultsControllerDelegate { var entityName : String! var predicate : NSPredicate! - var downloadDate: NSDate! + var downloadDate: Date! lazy var models: [LTEntityModel]! = { - return self.fetchedResultsController.fetchedObjects as? [LTEntityModel] + return self.fetchedResultsController.fetchedObjects }() // MARK: - NSFetchedResultsController - lazy var fetchedResultsController: NSFetchedResultsController = { - let fetchRequest = NSFetchRequest(entityName: self.entityName) + lazy var fetchedResultsController: NSFetchedResultsController = { () -> NSFetchedResultsController in + let fetchRequest = NSFetchRequest(entityName: self.entityName) fetchRequest.predicate = self.predicate fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] @@ -32,7 +32,7 @@ class LTArrayModel: NSObject, NSFetchedResultsControllerDelegate { return fetchedResultsController }() - init(entityName: String, predicate: NSPredicate, date: NSDate) { + init(entityName: String, predicate: NSPredicate, date: Date) { super.init() self.predicate = predicate @@ -46,9 +46,9 @@ class LTArrayModel: NSObject, NSFetchedResultsControllerDelegate { } //MARK: - Public - func filters(key: LTType, completionHandler:(result: [LTSectionModel], finish: Bool) -> Void) { + func filters(_ key: LTType, completionHandler:(_ result: [LTSectionModel], _ finish: Bool) -> Void) { if nil == models { - completionHandler(result: [LTSectionModel](), finish: true) + completionHandler([LTSectionModel](), true) return } @@ -98,7 +98,7 @@ class LTArrayModel: NSObject, NSFetchedResultsControllerDelegate { } } - completionHandler(result: filters, finish: true) + completionHandler(filters, true) } func count() -> Int { diff --git a/LawTracker/Sources/Models/LTChangeModel.swift b/LawTracker/Sources/Models/LTChangeModel.swift index c3f3e0e..6bdb592 100644 --- a/LawTracker/Sources/Models/LTChangeModel.swift +++ b/LawTracker/Sources/Models/LTChangeModel.swift @@ -17,19 +17,19 @@ class LTChangeModel: LTEntityModel { static let billModel = "billModel" } - @NSManaged var date : NSDate + @NSManaged var date : Date @NSManaged dynamic var law : LTLawModel - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext) { // Core Data - let entity = NSEntityDescription.entityForName("LTChangeModel", inManagedObjectContext: context)! - super.init(entity: entity, insertIntoManagedObjectContext: context) + let entity = NSEntityDescription.entity(forEntityName: "LTChangeModel", in: context)! + super.init(entity: entity, insertInto: context) - if let date = dictionary[Keys.changeDate] as? NSDate { + if let date = dictionary[Keys.changeDate] as? Date { self.date = date } @@ -46,11 +46,11 @@ class LTChangeModel: LTEntityModel { } } - class func changesForDate(date: NSDate) -> [LTChangeModel]? { - let predicate = NSPredicate(format:"date == %@", date) - let fetchRequest = NSFetchRequest(entityName: "LTChangeModel") + class func changesForDate(_ date: Date) -> [LTChangeModel]? { + let predicate = NSPredicate(format:"date == %@", date as CVarArg) + let fetchRequest = NSFetchRequest(entityName: "LTChangeModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTChangeModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTChangeModel] { return models.count > 0 ? models : nil } else { return nil diff --git a/LawTracker/Sources/Models/LTChangesModel.swift b/LawTracker/Sources/Models/LTChangesModel.swift index 230586c..6ceadb8 100644 --- a/LawTracker/Sources/Models/LTChangesModel.swift +++ b/LawTracker/Sources/Models/LTChangesModel.swift @@ -11,17 +11,17 @@ import Foundation class LTChangesModel: NSObject { var changes : [LTSectionModel] = [] var filtersApplied : Bool = false - var date : NSDate! + var date : Date! var type : LTType! override init() { super.init() self.changes = [] - self.date = NSDate() + self.date = Date() } - init(changes: [LTSectionModel], type: LTType, filtersApplied: Bool, date: NSDate) { + init(changes: [LTSectionModel], type: LTType, filtersApplied: Bool, date: Date) { super.init() self.changes = changes @@ -30,7 +30,7 @@ class LTChangesModel: NSObject { self.type = type } - func addModel(model: LTSectionModel) { + func addModel(_ model: LTSectionModel) { changes.append(model) } @@ -38,7 +38,7 @@ class LTChangesModel: NSObject { return changes.count } - func sectionWithEntities(entities:[LTEntityModel]) -> LTSectionModel? { + func sectionWithEntities(_ entities:[LTEntityModel]) -> LTSectionModel? { return changes.filter(){ $0.entities == entities }.first } diff --git a/LawTracker/Sources/Models/LTCommitteeModel.swift b/LawTracker/Sources/Models/LTCommitteeModel.swift index 6953261..83ef909 100644 --- a/LawTracker/Sources/Models/LTCommitteeModel.swift +++ b/LawTracker/Sources/Models/LTCommitteeModel.swift @@ -10,8 +10,8 @@ import CoreData class LTCommitteeModel: LTEntityModel { @NSManaged var url : String - @NSManaged var starts : NSDate? - @NSManaged var ends : NSDate? + @NSManaged var starts : Date? + @NSManaged var ends : Date? @NSManaged var laws : NSMutableSet @NSManaged var convocation : LTConvocationModel @@ -21,8 +21,8 @@ class LTCommitteeModel: LTEntityModel { } } - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } override init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { @@ -33,13 +33,13 @@ class LTCommitteeModel: LTEntityModel { } if let startsString = dictionary[Keys.starts] as? String { - if let startsDate = startsString.date() as NSDate! { + if let startsDate = startsString.date() as Date! { starts = startsDate } } if let endsString = dictionary[Keys.ends] as? String { - if let endsDate = endsString.date() as NSDate! { + if let endsDate = endsString.date() as Date! { ends = endsDate } } diff --git a/LawTracker/Sources/Models/LTConvocationModel.swift b/LawTracker/Sources/Models/LTConvocationModel.swift index 6d0032c..b367448 100644 --- a/LawTracker/Sources/Models/LTConvocationModel.swift +++ b/LawTracker/Sources/Models/LTConvocationModel.swift @@ -16,11 +16,11 @@ class LTConvocationModel: LTEntityModel { @NSManaged var laws : NSMutableSet @NSManaged var committees : NSMutableSet - class func convocationWithNumber(number: String) -> LTConvocationModel? { + class func convocationWithNumber(_ number: String) -> LTConvocationModel? { let predicate = NSPredicate(format:"number == %@", number) - let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") + let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as! [LTConvocationModel]! { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as! [LTConvocationModel]! { if models.count > 0 { return models.first! } else { @@ -32,10 +32,10 @@ class LTConvocationModel: LTEntityModel { } class func currentConvocation() -> LTConvocationModel? { - let predicate = NSPredicate(format:"current == %@", true) - let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") + let predicate = NSPredicate(format:"current == %@", true as CVarArg) + let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as! [LTConvocationModel]! { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as! [LTConvocationModel]! { if models.count > 0 { return models.first! } else { @@ -48,17 +48,17 @@ class LTConvocationModel: LTEntityModel { class func convocations() -> [LTConvocationModel] { let predicate = NSPredicate(value: true) - let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") + let fetchRequest = NSFetchRequest(entityName: "LTConvocationModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTConvocationModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTConvocationModel] { return models } else { return [] } } - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } override init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { diff --git a/LawTracker/Sources/Models/LTEntityModel.swift b/LawTracker/Sources/Models/LTEntityModel.swift index 1fa8748..69015c2 100644 --- a/LawTracker/Sources/Models/LTEntityModel.swift +++ b/LawTracker/Sources/Models/LTEntityModel.swift @@ -36,11 +36,11 @@ class LTEntityModel: NSManagedObject { var entityName: String! - class func modelWithID(id: String, entityName: String) -> LTEntityModel? { + class func modelWithID(_ id: String, entityName: String) -> LTEntityModel? { let predicate = NSPredicate(format:"id == %@", id) - let fetchRequest = NSFetchRequest(entityName: entityName) + let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTEntityModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTEntityModel] { if models.count > 0 { return models.first! } else { @@ -51,8 +51,8 @@ class LTEntityModel: NSManagedObject { } } - class func filteredEntities(key: LTType) -> [LTEntityModel]? { - let predicate = NSPredicate(format:"filterSet == %@", true) + class func filteredEntities(_ key: LTType) -> [LTEntityModel]? { + let predicate = NSPredicate(format:"filterSet == %@", true as CVarArg) var entityName = String() switch key { case .byLaws: @@ -68,23 +68,23 @@ class LTEntityModel: NSManagedObject { break } - let fetchRequest = NSFetchRequest(entityName: entityName) + let fetchRequest = NSFetchRequest(entityName: entityName) fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTEntityModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTEntityModel] { return models } else { return nil } } - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { // Core Data - let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: context)! - super.init(entity: entity, insertIntoManagedObjectContext: context) + let entity = NSEntityDescription.entity(forEntityName: entityName, in: context)! + super.init(entity: entity, insertInto: context) self.entityName = entityName @@ -99,11 +99,11 @@ class LTEntityModel: NSManagedObject { } } - func addValueForKey(value: AnyObject, key: String) { - if deleted { + func addValueForKey(_ value: AnyObject, key: String) { + if isDeleted { return } - mutableSetValueForKey(key).addObject(value) + mutableSetValue(forKey: key).add(value) } } diff --git a/LawTracker/Sources/Models/LTInitiatorModel.swift b/LawTracker/Sources/Models/LTInitiatorModel.swift index a831646..182cbf8 100644 --- a/LawTracker/Sources/Models/LTInitiatorModel.swift +++ b/LawTracker/Sources/Models/LTInitiatorModel.swift @@ -12,8 +12,8 @@ class LTInitiatorModel: LTEntityModel { @NSManaged var isDeputy : Bool @NSManaged var convocations : NSMutableSet - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } override init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { diff --git a/LawTracker/Sources/Models/LTInitiatorTypeModel.swift b/LawTracker/Sources/Models/LTInitiatorTypeModel.swift index 9aa6009..f0589e8 100644 --- a/LawTracker/Sources/Models/LTInitiatorTypeModel.swift +++ b/LawTracker/Sources/Models/LTInitiatorTypeModel.swift @@ -11,17 +11,17 @@ import CoreData class LTInitiatorTypeModel: LTEntityModel { @NSManaged var persons : NSMutableSet - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } override init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { super.init(dictionary: dictionary, context: context, entityName: entityName) if id != "deputy" { - let dictionary = ["id":id, "title":title, "isDeputy":"false", "convocations":NSMutableSet()] + let dictionary = ["id":id, "title":title, "isDeputy":"false", "convocations":NSMutableSet()] as [String : Any] - _ = LTInitiatorModel(dictionary: dictionary, context: context, entityName: "LTInitiatorModel") + _ = LTInitiatorModel(dictionary: dictionary as [String : AnyObject], context: context, entityName: "LTInitiatorModel") } } diff --git a/LawTracker/Sources/Models/LTLawModel.swift b/LawTracker/Sources/Models/LTLawModel.swift index 324d8da..cd8379f 100644 --- a/LawTracker/Sources/Models/LTLawModel.swift +++ b/LawTracker/Sources/Models/LTLawModel.swift @@ -10,7 +10,7 @@ import CoreData class LTLawModel: LTEntityModel { @NSManaged var number : String - @NSManaged var presentationDate : NSDate? + @NSManaged var presentationDate : Date? @NSManaged var url : String @NSManaged var changes : NSMutableSet @@ -19,8 +19,8 @@ class LTLawModel: LTEntityModel { @NSManaged var convocation : LTConvocationModel @NSManaged var committee : LTCommitteeModel - override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { - super.init(entity: entity, insertIntoManagedObjectContext: context) + override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) { + super.init(entity: entity, insertInto: context) } override init(dictionary: [String : AnyObject], context: NSManagedObjectContext, entityName: String) { @@ -35,7 +35,7 @@ class LTLawModel: LTEntityModel { } if let dateString = dictionary[Keys.date] as? String { - if let date = dateString.date() as NSDate! { + if let date = dateString.date() as Date! { self.presentationDate = date } } @@ -55,11 +55,11 @@ class LTLawModel: LTEntityModel { } } - class func lawWithNumber(number: String) -> LTLawModel? { + class func lawWithNumber(_ number: String) -> LTLawModel? { let predicate = NSPredicate(format:"number == %@", number) - let fetchRequest = NSFetchRequest(entityName: "LTLawModel") + let fetchRequest = NSFetchRequest(entityName: "LTLawModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTLawModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTLawModel] { if models.count > 0 { return models.first! } else { @@ -70,15 +70,15 @@ class LTLawModel: LTEntityModel { } } - class func changesForLaw(number: String) -> NSMutableSet? { + class func changesForLaw(_ number: String) -> NSMutableSet? { let predicate = NSPredicate(format:"number == %@", number) - let fetchRequest = NSFetchRequest(entityName: "LTLawModel") + let fetchRequest = NSFetchRequest(entityName: "LTLawModel") fetchRequest.predicate = predicate - if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.executeFetchRequest(fetchRequest)) as? [LTLawModel] { + if let models = (try? CoreDataStackManager.sharedInstance().managedObjectContext.fetch(fetchRequest)) as? [LTLawModel] { if models.count > 0 { let changes = models.first!.changes for change in changes { - print("DATE =", change.date) + print("DATE =", (change as AnyObject).date) } return changes diff --git a/LawTracker/Sources/Models/LTPersonModel.swift b/LawTracker/Sources/Models/LTPersonModel.swift index 062467d..99df2b4 100644 --- a/LawTracker/Sources/Models/LTPersonModel.swift +++ b/LawTracker/Sources/Models/LTPersonModel.swift @@ -55,7 +55,7 @@ struct LTPersonModel { if let firstName = firstName as String! { if let secondName = secondName as String! { if let lastName = lastName as String! { - self.fullName = [lastName, firstName, secondName].joinWithSeparator(" ") + self.fullName = [lastName, firstName, secondName].joined(separator: " ") } } } @@ -65,7 +65,7 @@ struct LTPersonModel { if let convocationsArray = dictionary[Keys.convocations] as? [String] { for convocation in convocationsArray { if let convocationModel = LTConvocationModel.convocationWithNumber(convocation) { - convocations.addObject(convocationModel) + convocations.add(convocationModel) } else { print("Cannot find convocation with id \(convocation)") } @@ -78,8 +78,8 @@ struct LTPersonModel { initiator = initiatorModel } else { if let fullName = fullName as String! { - let dictionary = ["id":id, "title":fullName, "isDeputy":"true", "convocations":convocations] - initiator = LTInitiatorModel(dictionary: dictionary, context: context, entityName: "LTInitiatorModel") + let dictionary = ["id":id, "title":fullName, "isDeputy":"true", "convocations":convocations] as [String : Any] + initiator = LTInitiatorModel(dictionary: dictionary as [String : AnyObject], context: context, entityName: "LTInitiatorModel") } } } diff --git a/LawTracker/Sources/Models/LTSectionModel.swift b/LawTracker/Sources/Models/LTSectionModel.swift index 0218395..8d90a6c 100644 --- a/LawTracker/Sources/Models/LTSectionModel.swift +++ b/LawTracker/Sources/Models/LTSectionModel.swift @@ -44,18 +44,18 @@ class LTSectionModel: NSObject { } } - self.title = titles.joinWithSeparator("\n") + self.title = titles.joined(separator: "\n") } - func newsModelWithEntity(entity: LTEntityModel) -> LTNewsModel? { + func newsModelWithEntity(_ entity: LTEntityModel) -> LTNewsModel? { return self.changes.filter(){ $0.entity == entity }.first } - func addModel(model: LTNewsModel) { + func addModel(_ model: LTNewsModel) { changes.append(model) } func count() -> Int { return changes.count } -} \ No newline at end of file +} diff --git a/LawTracker/Sources/Models/VTSettingModel.swift b/LawTracker/Sources/Models/VTSettingModel.swift index ea9f0e3..d1d7fd6 100644 --- a/LawTracker/Sources/Models/VTSettingModel.swift +++ b/LawTracker/Sources/Models/VTSettingModel.swift @@ -9,7 +9,7 @@ import MapKit class VTSettingModel: NSObject { - var defaults : NSUserDefaults + var defaults : UserDefaults struct Keys { static let FirstLaunch = "firstLaunch" @@ -18,21 +18,21 @@ class VTSettingModel: NSObject { var firstLaunch : Bool { get { - return defaults.boolForKey(Keys.FirstLaunch) + return defaults.bool(forKey: Keys.FirstLaunch) } set { - defaults.setBool(newValue, forKey: Keys.FirstLaunch) + defaults.set(newValue, forKey: Keys.FirstLaunch) } } - var lastDownloadDate : NSDate? { + var lastDownloadDate : Date? { set { - defaults.setObject(newValue!.dateWithoutTime(), forKey: Keys.Date) + defaults.set(newValue!.dateWithoutTime(), forKey: Keys.Date) } get { - if let date = defaults.objectForKey(Keys.Date) as? NSDate { + if let date = defaults.object(forKey: Keys.Date) as? Date { return date.dateWithoutTime() } else { return nil @@ -45,19 +45,19 @@ class VTSettingModel: NSObject { } override init() { - self.defaults = NSUserDefaults.standardUserDefaults() + self.defaults = UserDefaults.standard super.init() } - override func setNilValueForKey(key: String) { + override func setNilValueForKey(_ key: String) { synchronized(self, closure: { - self.defaults.removeObjectForKey(key) + self.defaults.removeObject(forKey: key) self.defaults.synchronize() }) } - override func setValue(value: AnyObject?, forKey key: String) { + override func setValue(_ value: Any?, forKey key: String) { synchronized(self, closure: { self.defaults.setValue(value, forKey: key) self.defaults.synchronize() diff --git a/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButton.swift b/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButton.swift index 7c6f8a9..6ad7e56 100644 --- a/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButton.swift +++ b/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButton.swift @@ -12,7 +12,7 @@ class LTSelectAllButton: UIButton { var view : LTSelectAllButtonView! var on: Bool! = false { didSet { - selected = on + isSelected = on if let selectAllButtonView = view as LTSelectAllButtonView! { selectAllButtonView.setOn(on) } diff --git a/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButtonView.swift b/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButtonView.swift index 012956d..e506968 100644 --- a/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButtonView.swift +++ b/LawTracker/Sources/UI/Buttons/LTSelectAllButton/LTSelectAllButtonView.swift @@ -20,7 +20,7 @@ class LTSelectAllButtonView: UIView { weak var rootView: UIView! - func setOn(on: Bool) { + func setOn(_ on: Bool) { if on { checkboxImageView.image = UIImage(named:selectedImageName) titleLabel.text = selectedTitle @@ -30,15 +30,15 @@ class LTSelectAllButtonView: UIView { } } - class func selectAllButtonView(rootView: UIView, selectedImageName: String, deselectedImageName: String, selectedTitle: String, deselectedTitle: String) -> LTSelectAllButtonView { - let selectAllButtonView = NSBundle.mainBundle().loadNibNamed("LTSelectAllButtonView", owner: self, options: nil).first as! LTSelectAllButtonView + class func selectAllButtonView(_ rootView: UIView, selectedImageName: String, deselectedImageName: String, selectedTitle: String, deselectedTitle: String) -> LTSelectAllButtonView { + let selectAllButtonView = Bundle.main.loadNibNamed("LTSelectAllButtonView", owner: self, options: nil)?.first as! LTSelectAllButtonView selectAllButtonView.selectedTitle = selectedTitle selectAllButtonView.deselectedTitle = deselectedTitle selectAllButtonView.selectedImageName = selectedImageName selectAllButtonView.deselectedImageName = deselectedImageName var frame = rootView.frame as CGRect - frame.origin = CGPointZero; + frame.origin = CGPoint.zero; selectAllButtonView.frame = frame; rootView.addSubview(selectAllButtonView) diff --git a/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButton.swift b/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButton.swift index 7e5857d..6dd8d1f 100644 --- a/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButton.swift +++ b/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButton.swift @@ -12,7 +12,7 @@ class LTSwitchButton: UIButton { var switchButtonView : LTSwitchButtonView! var on: Bool! = false { didSet { - selected = on + isSelected = on if let switchButtonView = switchButtonView as LTSwitchButtonView! { switchButtonView.setOn(on) } @@ -39,14 +39,14 @@ class LTSwitchButton: UIButton { } //MARK:- Public - func setFilterImage(key: LTType) { - dispatch_async(CoreDataStackManager.coreDataQueue()) {[unowned self] in + func setFilterImage(_ key: LTType) { + CoreDataStackManager.coreDataQueue().async {[unowned self] in if let filteredEntities = LTEntityModel.filteredEntities(key) as [LTEntityModel]! { - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { self.filtersSet = filteredEntities.count > 0 } } else { - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { self.filtersSet = false } } diff --git a/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButtonView.swift b/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButtonView.swift index 29f8f82..1e913cf 100644 --- a/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButtonView.swift +++ b/LawTracker/Sources/UI/Buttons/LTSwitchButton/LTSwitchButtonView.swift @@ -16,17 +16,17 @@ class LTSwitchButtonView: UIView { var selectedImageName : String! var deselectedImageName : String! - func filtersSet(set: Bool) { - switchImageView.hidden = !set + func filtersSet(_ set: Bool) { + switchImageView.isHidden = !set } weak var rootView: UIView! - class func switchButtonView(rootView: UIView, title: String, selectedImageName: String, deselectedImageName: String) -> LTSwitchButtonView { - let switchButtonView = NSBundle.mainBundle().loadNibNamed("LTSwitchButtonView", owner: self, options: nil).first as! LTSwitchButtonView + class func switchButtonView(_ rootView: UIView, title: String, selectedImageName: String, deselectedImageName: String) -> LTSwitchButtonView { + let switchButtonView = Bundle.main.loadNibNamed("LTSwitchButtonView", owner: self, options: nil)?.first as! LTSwitchButtonView switchButtonView.headerLabel.text = title var frame = rootView.frame as CGRect - frame.origin = CGPointZero; + frame.origin = CGPoint.zero; switchButtonView.frame = frame; switchButtonView.selectedImageName = selectedImageName switchButtonView.deselectedImageName = deselectedImageName @@ -43,14 +43,14 @@ class LTSwitchButtonView: UIView { headerLabel.font = headerLabel.font.screenProportionalFont() } - func setOn(on: Bool) { + func setOn(_ on: Bool) { if on { - backgroundView.backgroundColor = UIColor.whiteColor() + backgroundView.backgroundColor = UIColor.white headerLabel.textColor = UIColor(red: 61.0/255.0, green: 29.0/255.0, blue: 92.0/255.0, alpha: 1.0) switchImageView.image = UIImage(named: selectedImageName) } else { backgroundView.backgroundColor = UIColor(red: 236.0/255.0, green: 233.0/255.0, blue: 239.0/255.0, alpha: 1.0) - headerLabel.textColor = UIColor.darkGrayColor() + headerLabel.textColor = UIColor.darkGray switchImageView.image = UIImage(named: deselectedImageName) } } diff --git a/LawTracker/Sources/UI/FilterViewController/LTFilterRootView.swift b/LawTracker/Sources/UI/FilterViewController/LTFilterRootView.swift index 89534a0..ce87779 100644 --- a/LawTracker/Sources/UI/FilterViewController/LTFilterRootView.swift +++ b/LawTracker/Sources/UI/FilterViewController/LTFilterRootView.swift @@ -25,7 +25,7 @@ class LTFilterRootView: UIView { super.awakeFromNib() //setup searchBar - searchBar.returnKeyType = .Done + searchBar.returnKeyType = .done searchBar.scopeButtonTitles = ["Всі", "Обрані", "Необрані"] if let label = okButton.titleLabel { @@ -37,11 +37,11 @@ class LTFilterRootView: UIView { } } - func fillSearchBar(text: String?) { + func fillSearchBar(_ text: String?) { searchBar.text = text } - func fillSearchBarPlaceholder(string: String) { + func fillSearchBarPlaceholder(_ string: String) { searchBar.placeholder = string } diff --git a/LawTracker/Sources/UI/FilterViewController/LTFilterTableViewCell.swift b/LawTracker/Sources/UI/FilterViewController/LTFilterTableViewCell.swift index c557707..93bd2c6 100644 --- a/LawTracker/Sources/UI/FilterViewController/LTFilterTableViewCell.swift +++ b/LawTracker/Sources/UI/FilterViewController/LTFilterTableViewCell.swift @@ -18,15 +18,15 @@ class LTFilterTableViewCell: UITableViewCell { } } - func fillWithModel(model: LTFilterCellModel) { + func fillWithModel(_ model: LTFilterCellModel) { let entity = model.entity filtered = model.selected - titleLabel.text = entity.title + titleLabel.text = entity?.title if let committee = entity as? LTCommitteeModel { if committee.expired { - userInteractionEnabled = false - titleLabel.textColor = UIColor.darkGrayColor() + isUserInteractionEnabled = false + titleLabel.textColor = UIColor.darkGray } } } diff --git a/LawTracker/Sources/UI/FilterViewController/LTFilterViewController.swift b/LawTracker/Sources/UI/FilterViewController/LTFilterViewController.swift index 7ea8234..7ee2491 100644 --- a/LawTracker/Sources/UI/FilterViewController/LTFilterViewController.swift +++ b/LawTracker/Sources/UI/FilterViewController/LTFilterViewController.swift @@ -38,7 +38,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi var rootView: LTFilterRootView! { get { - if isViewLoaded() && view.isKindOfClass(LTFilterRootView) { + if isViewLoaded && view.isKind(of: LTFilterRootView.self) { return view as? LTFilterRootView } else { return nil @@ -46,38 +46,38 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi } } - override func prefersStatusBarHidden() -> Bool { + override var prefersStatusBarHidden : Bool { return true } - override func viewWillAppear(animated: Bool) { + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) rootView.fillSearchBarPlaceholder(placeholderString) } - override func viewWillDisappear(animated: Bool) { + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) rootView.endEditing(true) } //MARK: - Interface Handling - @IBAction func onOkButton(sender: AnyObject) { + @IBAction func onOkButton(_ sender: AnyObject) { setFilters {[unowned self] (finished) -> Void in if finished { - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { if let filterDelegate = self.filterDelegate { filterDelegate.filtersDidApplied() } - self.dismissViewControllerAnimated(true, completion: nil) + self.dismiss(animated: true, completion: nil) } } } } - @IBAction func onCancelButton(sender: AnyObject) { + @IBAction func onCancelButton(_ sender: AnyObject) { //clear filters in Settings if let filters = filters as [LTSectionModel]! { for sectionModel in filters { @@ -89,16 +89,16 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi CoreDataStackManager.sharedInstance().saveContext() } - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + DispatchQueue.main.async {[unowned self] in if let filterDelegate = self.filterDelegate { filterDelegate.filtersDidApplied() } - self.dismissViewControllerAnimated(true, completion: nil) + self.dismiss(animated: true, completion: nil) } } - @IBAction func onSelectAllButton(sender: AnyObject) { + @IBAction func onSelectAllButton(_ sender: AnyObject) { rootView.endEditing(true) if let filters = filters as [LTSectionModel]! { @@ -126,7 +126,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi } func headerTapped() { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView] in + DispatchQueue.main.async {[unowned self, weak rootView = rootView] in if let filters = self.filters as [LTSectionModel]! { rootView!.endEditing(true) let deputiesArray = filters.filter(){ $0.title == "Народні депутати України" }.first @@ -137,13 +137,13 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi } let searchBar = rootView!.searchBar - self.filterContentForSearchText(searchBar.text!, scope: searchBar.selectedScopeButtonIndex) + self.filterContentForSearchText((searchBar?.text!)!, scope: (searchBar?.selectedScopeButtonIndex)!) } } } //MARK: - UITableViewDataSource methods - func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let filters = filters as [LTSectionModel]! { let sectionModel = rootView.searchBarActive ? filteredArray[section] : filters[section] @@ -153,7 +153,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi return 0 } - func numberOfSectionsInTableView(tableView: UITableView) -> Int { + func numberOfSections(in tableView: UITableView) -> Int { if let filters = filters as [LTSectionModel]! { return rootView.searchBarActive ? filteredArray.count : filters.count } @@ -161,8 +161,8 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi return 0 } - func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("LTFilterTableViewCell", forIndexPath: indexPath) as! LTFilterTableViewCell + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "LTFilterTableViewCell", for: indexPath) as! LTFilterTableViewCell if let filters = filters as [LTSectionModel]! { let model = rootView.searchBarActive ? filteredArray[indexPath.section].filters[indexPath.row] : filters[indexPath.section].filters[indexPath.row] @@ -172,7 +172,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi return cell } - func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let filters = filters as [LTSectionModel]! { return rootView.searchBarActive ? filteredArray[section].title : filters[section].title } @@ -180,14 +180,14 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi return nil } - func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let filters = filters as [LTSectionModel]! { let headerView = LTCellHeaderView.headerView() as LTCellHeaderView let title = rootView.searchBarActive ? filteredArray[section].title : filters[section].title headerView.fillWithString(title) let button = UIButton() button.frame = headerView.frame - button.addTarget(self, action: "headerTapped", forControlEvents: .TouchUpInside) + button.addTarget(self, action: #selector(LTFilterViewController.headerTapped), for: .touchUpInside) headerView.addSubview(button) return headerView @@ -196,7 +196,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi return nil } - func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { + func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if let filters = filters as [LTSectionModel]! { let title = rootView.searchBarActive ? filteredArray[section].title : filters[section].title @@ -207,52 +207,52 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi } //MARK: - UITableViewDelegate methods - func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView] in + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + DispatchQueue.main.async {[unowned self, weak rootView = rootView] in rootView!.endEditing(true) if let filters = self.filters as [LTSectionModel]! { let searchBar = rootView!.searchBar let array = rootView!.searchBarActive ? self.filteredArray[indexPath.section].filters : filters[indexPath.section].filters - let cell = tableView.cellForRowAtIndexPath(indexPath) as! LTFilterTableViewCell + let cell = tableView.cellForRow(at: indexPath) as! LTFilterTableViewCell let selectedModel = array[indexPath.row] selectedModel.selected = !cell.filtered - self.filterContentForSearchText(searchBar.text!, scope: searchBar.selectedScopeButtonIndex) + self.filterContentForSearchText((searchBar?.text!)!, scope: (searchBar?.selectedScopeButtonIndex)!) } } } //MARK: - UISearchBarDelegate - func searchBar(searchBar: UISearchBar, textDidChange searchText: String) { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { + DispatchQueue.main.async {[unowned self] in self.filterContentForSearchText(searchText, scope: searchBar.selectedScopeButtonIndex) } } - func searchBar(searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) { + DispatchQueue.main.async {[unowned self] in self.filterContentForSearchText(searchBar.text!, scope: selectedScope) } } - func searchBarSearchButtonClicked(searchBar: UISearchBar) { - dispatch_async(dispatch_get_main_queue()) { + func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { + DispatchQueue.main.async { searchBar.resignFirstResponder() } } - func searchBarCancelButtonClicked(searchBar: UISearchBar) { - dispatch_async(dispatch_get_main_queue()) { + func searchBarCancelButtonClicked(_ searchBar: UISearchBar) { + DispatchQueue.main.async { searchBar.resignFirstResponder() } } //MARK: - Private methods - private func filterContentForSearchText(searchText: String, scope: Int = 0) { + fileprivate func filterContentForSearchText(_ searchText: String, scope: Int = 0) { if let filters = filters as [LTSectionModel]! { filteredArray = [LTSectionModel]() for sectionModel in filters { @@ -260,9 +260,9 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi let category = filter.selected == true ? 1 : 2 let categoryMatch = (scope == 0) || (category == scope) if searchText != "" { - let containsInTitle = filter.entity.title.lowercaseString.containsString(searchText.lowercaseString) + let containsInTitle = filter.entity.title.lowercased().contains(searchText.lowercased()) if let entity = filter.entity as? LTLawModel { - let containsInNumber = entity.number.lowercaseString.containsString(searchText.lowercaseString) + let containsInNumber = entity.number.lowercased().contains(searchText.lowercased()) return categoryMatch && (containsInTitle || containsInNumber) } else { @@ -282,15 +282,15 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi } } - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.tableView.reloadData() } } } - private func setFilters(completionHandler:(finished: Bool) -> Void) { + fileprivate func setFilters(_ completionHandler:@escaping (_ finished: Bool) -> Void) { let queue = CoreDataStackManager.coreDataQueue() - dispatch_async(queue) { + queue.async { if let filters = self.filters as [LTSectionModel]! { for sectionModel in filters { for filter in sectionModel.filters { @@ -301,7 +301,7 @@ class LTFilterViewController: UIViewController, UITableViewDataSource, UITableVi CoreDataStackManager.sharedInstance().saveContext() } - completionHandler(finished: true) + completionHandler(true) } } diff --git a/LawTracker/Sources/UI/LTGestureRecognizer/LTPanGestureRacognizer.swift b/LawTracker/Sources/UI/LTGestureRecognizer/LTPanGestureRacognizer.swift index 0b2e542..8190981 100644 --- a/LawTracker/Sources/UI/LTGestureRecognizer/LTPanGestureRacognizer.swift +++ b/LawTracker/Sources/UI/LTGestureRecognizer/LTPanGestureRacognizer.swift @@ -9,13 +9,13 @@ import UIKit enum LTPanDirection: Int { - case Unknown = 0, - Right, - Left, - Up, - Down + case unknown = 0, + right, + left, + up, + down - static let cellTypes = [Unknown, Right, Left, Up, Down] + static let cellTypes = [unknown, right, left, up, down] }; class LTPanGestureRacognizer: UIPanGestureRecognizer { @@ -24,28 +24,28 @@ class LTPanGestureRacognizer: UIPanGestureRecognizer { //MARK: - Public methods func changeDirection() { - let translation = translationInView(view) - direction = CGPointEqualToPoint(CGPointZero, translation) ? directionForTranslation(velocityInView(view)) : directionForTranslation(translation) - startLocation = locationInView(view) + let translation = self.translation(in: view) + direction = CGPoint.zero.equalTo(translation) ? directionForTranslation(velocity(in: view)) : directionForTranslation(translation) + startLocation = location(in: view) } func reset() { - direction = .Unknown - startLocation = CGPointZero + direction = .unknown + startLocation = CGPoint.zero } //MARK: - Private methods - func directionForTranslation(translation: CGPoint) -> LTPanDirection { - let frame = CGRectMake(0, 0, translation.x, translation.y) - let verticalOffset = CGRectGetHeight(frame) - let horizontalOffset = CGRectGetWidth(frame) + func directionForTranslation(_ translation: CGPoint) -> LTPanDirection { + let frame = CGRect(x: 0, y: 0, width: translation.x, height: translation.y) + let verticalOffset = frame.height + let horizontalOffset = frame.width if verticalOffset < horizontalOffset { - return translation.x > 0 ? .Right : .Left + return translation.x > 0 ? .right : .left } else if verticalOffset > horizontalOffset { - return translation.y > 0 ? .Down : .Up + return translation.y > 0 ? .down : .up } - return .Unknown + return .unknown } } diff --git a/LawTracker/Sources/UI/LTHelpController/LTHelpContentController.swift b/LawTracker/Sources/UI/LTHelpController/LTHelpContentController.swift index fc9178d..155d6b2 100644 --- a/LawTracker/Sources/UI/LTHelpController/LTHelpContentController.swift +++ b/LawTracker/Sources/UI/LTHelpController/LTHelpContentController.swift @@ -12,7 +12,7 @@ class LTHelpContentController: UIViewController { var rootView: LTHelpContentView? { get { - if isViewLoaded() && view.isKindOfClass(LTHelpContentView) { + if isViewLoaded && view.isKind(of: LTHelpContentView.self) { return view as? LTHelpContentView } else { return nil @@ -24,20 +24,20 @@ class LTHelpContentController: UIViewController { var pageIndex : Int! - override func viewWillAppear(animated: Bool) { + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) rootView!.fill(model) } - override func prefersStatusBarHidden() -> Bool { + override var prefersStatusBarHidden : Bool { return true } - override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { - super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) + override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { + super.viewWillTransition(to: size, with: coordinator) - coordinator.animateAlongsideTransition({[weak rootView = rootView] (UIViewControllerTransitionCoordinatorContext) -> Void in + coordinator.animate(alongsideTransition: {[weak rootView = rootView] (UIViewControllerTransitionCoordinatorContext) -> Void in if let rootView = rootView as LTHelpContentView! { rootView.fill(self.model) }}, completion: {(UIViewControllerTransitionCoordinatorContext) -> Void in }) diff --git a/LawTracker/Sources/UI/LTHelpController/LTHelpContentView.swift b/LawTracker/Sources/UI/LTHelpController/LTHelpContentView.swift index cf111be..f4321b6 100644 --- a/LawTracker/Sources/UI/LTHelpController/LTHelpContentView.swift +++ b/LawTracker/Sources/UI/LTHelpController/LTHelpContentView.swift @@ -12,8 +12,8 @@ class LTHelpContentView: UIView { @IBOutlet var contentImageView: UIImageView! - func fill(model: [String]) { - if .Portrait == UIApplication.sharedApplication().statusBarOrientation { + func fill(_ model: [String]) { + if .portrait == UIApplication.shared.statusBarOrientation { contentImageView.image = UIImage(named: model.first!) } else { contentImageView.image = UIImage(named: model.last!) diff --git a/LawTracker/Sources/UI/LTHelpController/LTHelpController.swift b/LawTracker/Sources/UI/LTHelpController/LTHelpController.swift index f79077c..e06c25f 100644 --- a/LawTracker/Sources/UI/LTHelpController/LTHelpController.swift +++ b/LawTracker/Sources/UI/LTHelpController/LTHelpController.swift @@ -39,7 +39,7 @@ class LTHelpController: UIViewController, UIPageViewControllerDataSource, UIPage var rootView: LTHelpView? { get { - if isViewLoaded() && view.isKindOfClass(LTHelpView) { + if isViewLoaded && view.isKind(of: LTHelpView.self) { return view as? LTHelpView } else { return nil @@ -73,16 +73,16 @@ class LTHelpController: UIViewController, UIPageViewControllerDataSource, UIPage super.viewDidLoad() automaticallyAdjustsScrollViewInsets = false - let pageViewController = storyboard!.instantiateViewControllerWithIdentifier("PageViewController") as! UIPageViewController + let pageViewController = storyboard!.instantiateViewController(withIdentifier: "PageViewController") as! UIPageViewController pageViewController.delegate = self pageViewController.dataSource = self if let firstItem = itemViewControllers.first as LTHelpContentController! { - pageViewController.setViewControllers([firstItem], direction: .Forward, animated: true) {[weak pageViewController = pageViewController] (finished) -> Void in + pageViewController.setViewControllers([firstItem], direction: .forward, animated: true) {[weak pageViewController = pageViewController] (finished) -> Void in if finished { if let pageViewController = pageViewController as UIPageViewController! { - dispatch_async(dispatch_get_main_queue()) { - pageViewController.setViewControllers([firstItem], direction: .Forward, animated: false, completion: nil) + DispatchQueue.main.async { + pageViewController.setViewControllers([firstItem], direction: .forward, animated: false, completion: nil) } } } @@ -95,55 +95,55 @@ class LTHelpController: UIViewController, UIPageViewControllerDataSource, UIPage } } - override func viewWillAppear(animated: Bool) { + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) //add swipe gecture recognizers - let upGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "onSwipe:") - upGestureRecognizer.direction = .Up + let upGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(LTHelpController.onSwipe(_:))) + upGestureRecognizer.direction = .up pageViewController.view.addGestureRecognizer(upGestureRecognizer) upSwipeGestureRecognizer = upGestureRecognizer - let downGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "onSwipe:") - downGestureRecognizer.direction = .Down + let downGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(LTHelpController.onSwipe(_:))) + downGestureRecognizer.direction = .down pageViewController.view.addGestureRecognizer(downGestureRecognizer) downSwipeGestureRecognizer = downGestureRecognizer } - override func viewWillDisappear(animated: Bool) { + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //remove swipe gecture recognizers - upSwipeGestureRecognizer.removeTarget(self, action: "onSwipe:") - downSwipeGestureRecognizer.removeTarget(self, action: "onSwipe:") + upSwipeGestureRecognizer.removeTarget(self, action: #selector(LTHelpController.onSwipe(_:))) + downSwipeGestureRecognizer.removeTarget(self, action: #selector(LTHelpController.onSwipe(_:))) pageViewController.view.removeGestureRecognizer(upSwipeGestureRecognizer) pageViewController.view.removeGestureRecognizer(downSwipeGestureRecognizer) } - override func prefersStatusBarHidden() -> Bool { + override var prefersStatusBarHidden : Bool { return true } //MARK: - Interface Handling - @IBAction func onSwipe(sender: UISwipeGestureRecognizer) { - if .Up == sender.direction || .Down == sender.direction { + @IBAction func onSwipe(_ sender: UISwipeGestureRecognizer) { + if .up == sender.direction || .down == sender.direction { onCloseButton(sender) } } - @IBAction func onCloseButton(sender: AnyObject) { + @IBAction func onCloseButton(_ sender: AnyObject) { if let navigationController = navigationController as UINavigationController! { - let newsFeedController = self.storyboard!.instantiateViewControllerWithIdentifier("LTNewsFeedViewController") as! LTNewsFeedViewController + let newsFeedController = self.storyboard!.instantiateViewController(withIdentifier: "LTNewsFeedViewController") as! LTNewsFeedViewController navigationController.viewControllers = [newsFeedController] } else { - dismissViewControllerAnimated(true, completion: nil) + dismiss(animated: true, completion: nil) } } //MARK: - UIPageViewControllerDataSource - func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? { + func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index: Int = (viewController as! LTHelpContentController).pageIndex - 1 if pageIsAnimating || NSNotFound == index { @@ -153,13 +153,14 @@ class LTHelpController: UIViewController, UIPageViewControllerDataSource, UIPage if index == itemViewControllers.count - 1 { return itemViewControllers.first } - - let destinationController = itemViewControllers[++index] + + index += 1 + let destinationController = itemViewControllers[index] return destinationController } - func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? { + func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index: Int = (viewController as! LTHelpContentController).pageIndex - 1 if pageIsAnimating || NSNotFound == index { @@ -169,21 +170,22 @@ class LTHelpController: UIViewController, UIPageViewControllerDataSource, UIPage if index == 0 { return itemViewControllers.last } - - let destinationController = itemViewControllers[--index] + + index -= 1 + let destinationController = itemViewControllers[index] return destinationController } //MARK: - UIPageViewControllerDelegate - func pageViewController(pageViewController: UIPageViewController, willTransitionToViewControllers pendingViewControllers: [UIViewController]) { + func pageViewController(_ pageViewController: UIPageViewController, willTransitionTo pendingViewControllers: [UIViewController]) { pageIsAnimating = true if let controller = pendingViewControllers.first as? LTHelpContentController! { pendingIndex = controller.pageIndex } } - func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { + func pageViewController(_ pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) { if finished && completed { pageIsAnimating = false if let rootView = rootView as LTHelpView! { diff --git a/LawTracker/Sources/UI/MainContentViewController/LTCellHeaderView.swift b/LawTracker/Sources/UI/MainContentViewController/LTCellHeaderView.swift index f02dd33..d9714bf 100644 --- a/LawTracker/Sources/UI/MainContentViewController/LTCellHeaderView.swift +++ b/LawTracker/Sources/UI/MainContentViewController/LTCellHeaderView.swift @@ -12,7 +12,7 @@ class LTCellHeaderView: UIView { @IBOutlet var titleLabel: UILabel! class func headerView() -> LTCellHeaderView { - let headerView = NSBundle.mainBundle().loadNibNamed("LTCellHeaderView", owner: self, options: nil).first as! LTCellHeaderView + let headerView = Bundle.main.loadNibNamed("LTCellHeaderView", owner: self, options: nil)?.first as! LTCellHeaderView return headerView } @@ -23,7 +23,7 @@ class LTCellHeaderView: UIView { titleLabel.text = "" } - func fillWithString(title: String) { + func fillWithString(_ title: String) { titleLabel.text = title titleLabel.fit() } diff --git a/LawTracker/Sources/UI/MainContentViewController/LTMainContentTableViewCell.swift b/LawTracker/Sources/UI/MainContentViewController/LTMainContentTableViewCell.swift index dd8c330..0715d4a 100644 --- a/LawTracker/Sources/UI/MainContentViewController/LTMainContentTableViewCell.swift +++ b/LawTracker/Sources/UI/MainContentViewController/LTMainContentTableViewCell.swift @@ -16,7 +16,7 @@ class LTMainContentTableViewCell: UITableViewCell { var model : LTNewsModel! - override func setSelected(selected: Bool, animated: Bool) { + override func setSelected(_ selected: Bool, animated: Bool) { } @@ -27,7 +27,7 @@ class LTMainContentTableViewCell: UITableViewCell { lawNameLabel.text = "" } - func fillWithModel(model: LTNewsModel) { + func fillWithModel(_ model: LTNewsModel) { self.model = model newsLabel.text = model.status @@ -39,12 +39,12 @@ class LTMainContentTableViewCell: UITableViewCell { addSeparator() } - private func addSeparator() { + fileprivate func addSeparator() { if let separatorView = self.separatorView as UIView! { separatorView.removeFromSuperview() } - separatorView = UIView(frame: CGRectMake(0, CGRectGetHeight(contentView.frame) - 1.2, CGRectGetWidth(contentView.frame), 0.8)) + separatorView = UIView(frame: CGRect(x: 0, y: contentView.frame.height - 1.2, width: contentView.frame.width, height: 0.8)) separatorView!.backgroundColor = UIColor(red: 233.0/255.0, green: 235.0/255.0, blue: 233.0/255.0, alpha: 1.0) contentView.addSubview(separatorView!) diff --git a/LawTracker/Sources/UI/MainContentViewController/LTMainContentViewController.swift b/LawTracker/Sources/UI/MainContentViewController/LTMainContentViewController.swift index 003c570..11e17b2 100644 --- a/LawTracker/Sources/UI/MainContentViewController/LTMainContentViewController.swift +++ b/LawTracker/Sources/UI/MainContentViewController/LTMainContentViewController.swift @@ -10,7 +10,7 @@ import CoreData import UIKit class LTMainContentViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate { - var loadingDate : NSDate? { + var loadingDate : Date? { didSet { if loadingDate != oldValue { setArrayModel() @@ -23,17 +23,17 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa if let arrayModel = arrayModel as LTChangesModel! { //reload data if let rootView = rootView as LTMainContentRootView! { - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.contentTableView.reloadData() } } //notify observers var userInfo = [String: AnyObject]() - userInfo["needLoadChangesForAnotherDay"] = 0 == arrayModel.count() + userInfo["needLoadChangesForAnotherDay"] = (0 == arrayModel.count()) as AnyObject - dispatch_async(dispatch_get_main_queue()) { - NSNotificationCenter.defaultCenter().postNotificationName("loadChangesForAnotherDate", object: nil, userInfo: userInfo) + DispatchQueue.main.async { + NotificationCenter.default.post(name: Notification.Name(rawValue: "loadChangesForAnotherDate"), object: nil, userInfo: userInfo) } } } @@ -50,7 +50,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa var rootView : LTMainContentRootView? { get { - if isViewLoaded() && view.isKindOfClass(LTMainContentRootView) { + if isViewLoaded && view.isKind(of: LTMainContentRootView.self) { return view as? LTMainContentRootView } else { return nil @@ -65,8 +65,8 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } // MARK: - NSFetchedResultsController - lazy var fetchedResultsController: NSFetchedResultsController = {[unowned self] in - let fetchRequest = NSFetchRequest(entityName: "LTChangeModel") + lazy var fetchedResultsController = { () -> NSFetchedResultsController in + let fetchRequest = NSFetchRequest(entityName: "LTChangeModel") fetchRequest.sortDescriptors = [NSSortDescriptor(key: "id", ascending: false)] let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, @@ -78,34 +78,34 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa }() //MARK: - View Life Cycle - override func prefersStatusBarHidden() -> Bool { + override var prefersStatusBarHidden : Bool { return true } //MARK: - gestureRecognizers - @IBAction func onLongTapGestureRecognizer(sender: UILongPressGestureRecognizer) { + @IBAction func onLongTapGestureRecognizer(_ sender: UILongPressGestureRecognizer) { if nil == rootView || nil == arrayModel { return } - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView, weak arrayModel = arrayModel] in + DispatchQueue.main.async {[unowned self, weak rootView = rootView, weak arrayModel = arrayModel] in //find indexPath for selected row let tableView = rootView!.contentTableView - let tapLocation = sender.locationInView(tableView) - if let indexPath = tableView.indexPathForRowAtPoint(tapLocation) as NSIndexPath! { + let tapLocation = sender.location(in: tableView) + if let indexPath = tableView?.indexPathForRow(at: tapLocation) as IndexPath! { //model for selected row let section = arrayModel!.changes[indexPath.section] let model = section.changes[indexPath.row].entity //complete sharing text - let law = model.law + let law = model?.law var initiators = [String]() - for initiator in law.initiators { - initiators.append(initiator.title!!) + for initiator in (law?.initiators)! { + initiators.append((initiator as AnyObject).title!!) } - let titles:[NSAttributedString] = [model.date.longString().attributedTitle()!, model.title.attributedTitle()!, "Законопроект #\(law.number)".attributedTitle()!, law.title.attributedText()!, "Ініціатор(и):".attributedTitle()!, initiators.joinWithSeparator(", ").attributedText()!, "Головний комітет:".attributedTitle()!, law.committee.title.attributedText()!] + let titles:[NSAttributedString] = [model!.date.longString().attributedTitle()!, model!.title.attributedTitle()!, "Законопроект #\(law!.number)".attributedTitle()!, law!.title.attributedText()!, "Ініціатор(и):".attributedTitle()!, initiators.joined(separator: ", ").attributedText()!, "Головний комітет:".attributedTitle()!, law!.committee.title.attributedText()!] let text = titles.joinWithSeparator("\n".attributedText()!) - let url = law.url.attributedLink()! + let url = law!.url.attributedLink()! let shareItems = [text, url] @@ -114,12 +114,12 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa return } - self.presentViewController(activityViewController, animated: true, completion: nil) + self.present(activityViewController, animated: true, completion: nil) - if UI_USER_INTERFACE_IDIOM() == .Pad { + if UI_USER_INTERFACE_IDIOM() == .pad { if let popoverViewController = activityViewController.popoverPresentationController { - popoverViewController.permittedArrowDirections = .Any - popoverViewController.sourceRect = CGRectMake(UIScreen.mainScreen().bounds.width / 2, UIScreen.mainScreen().bounds.height / 4, 0, 0) + popoverViewController.permittedArrowDirections = .any + popoverViewController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 4, width: 0, height: 0) popoverViewController.sourceView = rootView } } @@ -128,7 +128,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } //MARK: - UITableViewDataSource methods - func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if let arrayModel = arrayModel as LTChangesModel! { return arrayModel.changes[section].changes.count } else { @@ -136,11 +136,11 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - func numberOfSectionsInTableView(tableView: UITableView) -> Int { + func numberOfSections(in tableView: UITableView) -> Int { if let rootView = rootView as LTMainContentRootView! { if let model = arrayModel { let count = model.changes.count - rootView.noSubscriptionsLabel.hidden = count > 0 + rootView.noSubscriptionsLabel.isHidden = count > 0 rootView.noSubscriptionsLabel.text = "Немає данних щодо змін статусів законопроектів на цей день." return count @@ -150,13 +150,13 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa return 0 } - func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.reusableCell(cellClass, indexPath: indexPath) as! LTMainContentTableViewCell if let arrayModel = arrayModel as LTChangesModel! { if arrayModel.changes.count > indexPath.section { let model = arrayModel.changes[indexPath.section] - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { if model.changes.count > indexPath.row { cell.fillWithModel(model.changes[indexPath.row]) } @@ -167,7 +167,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa return cell } - func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { + func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if let arrayModel = arrayModel as LTChangesModel! { if arrayModel.changes.count > section { return arrayModel.changes[section].title @@ -177,10 +177,10 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa return nil } - func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { + func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if let arrayModel = arrayModel as LTChangesModel! { let headerView = LTCellHeaderView.headerView() as LTCellHeaderView - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { if arrayModel.changes.count > section { headerView.fillWithString(arrayModel.changes[section].title) } @@ -194,14 +194,14 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } //MARK: - UITableViewDelegate methods - func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let arrayModel = arrayModel as LTChangesModel! { if arrayModel.changes.count > indexPath.section { let sectionModel = arrayModel.changes[indexPath.section] if sectionModel.changes.count > indexPath.row { let changeModel = sectionModel.changes[indexPath.row].entity - if let url = NSURL(string: changeModel.law.url) as NSURL! { - let app = UIApplication.sharedApplication() + if let url = URL(string: (changeModel?.law.url)!) as URL! { + let app = UIApplication.shared if app.canOpenURL(url) { app.openURL(url) } @@ -211,13 +211,13 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { + func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if let arrayModel = arrayModel as LTChangesModel! { if arrayModel.changes.count > indexPath.section { let changes = arrayModel.changes[indexPath.section].changes if changes.count > indexPath.row { let changeModel = changes[indexPath.row] - let width = CGRectGetWidth(tableView.frame) - 20.0 + let width = tableView.frame.width - 20.0 let descriptionFont = UIFont(name: "Arial-BoldMT", size: 14.0) let lawNameHeight = changeModel.billName.getHeight(width, font: descriptionFont!) let descriptionHeight = changeModel.status.getHeight(width, font: descriptionFont!) @@ -232,11 +232,11 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa //MARK: - Public func arrayModelFromChanges() { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak loadingDate = loadingDate] in - if let loadingDate = loadingDate as NSDate! { + DispatchQueue.main.async {[unowned self, loadingDate = loadingDate] in + if let loadingDate = loadingDate as Date! { if let type = self.type as LTType! { let changesList = self.sectionModelsByKey(type) - let arrayModel = LTChangesModel(changes: changesList, type: type, filtersApplied: false, date: loadingDate) + let arrayModel = LTChangesModel(changes: changesList!, type: type, filtersApplied: false, date: loadingDate) self.applyFilters(arrayModel, completionHandler: { (result, finish) -> Void in self.arrayModel = result @@ -246,8 +246,8 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - func applyFilters(arrayModel: LTChangesModel, completionHandler:(arrayModel: LTChangesModel, finish: Bool) -> Void) { - dispatch_async(CoreDataStackManager.coreDataQueue()) { + func applyFilters(_ arrayModel: LTChangesModel, completionHandler:@escaping (_ arrayModel: LTChangesModel, _ finish: Bool) -> Void) { + CoreDataStackManager.coreDataQueue().async { if let filters = LTEntityModel.filteredEntities(arrayModel.type) as [LTEntityModel]! { if filters.count > 0 { var filteredSections = [LTSectionModel]() @@ -259,18 +259,18 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - completionHandler(arrayModel: LTChangesModel(changes: filteredSections, type: arrayModel.type, filtersApplied: true, date: arrayModel.date), finish: true) + completionHandler(LTChangesModel(changes: filteredSections, type: arrayModel.type, filtersApplied: true, date: arrayModel.date), true) return } } - completionHandler(arrayModel: arrayModel, finish: true) + completionHandler(arrayModel, true) } } - func applyFiltersForSection(sectionModel: LTSectionModel, completionHandler:(result: LTSectionModel?, finish: Bool) -> Void) { - dispatch_async(CoreDataStackManager.coreDataQueue()) {[unowned self] in + func applyFiltersForSection(_ sectionModel: LTSectionModel, completionHandler:@escaping (_ result: LTSectionModel?, _ finish: Bool) -> Void) { + CoreDataStackManager.coreDataQueue().async {[unowned self] in if let type = self.type as LTType! { if let filters = LTEntityModel.filteredEntities(type) as [LTEntityModel]! { if filters.count > 0 { @@ -282,22 +282,22 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - completionHandler(result: result, finish: true) + completionHandler(result, true) return } - completionHandler(result: nil, finish: true) + completionHandler(nil, true) } } else { - completionHandler(result: sectionModel, finish: true) + completionHandler(sectionModel, true) } } } //MARK: - Private - private func sectionModelsByKey(key: LTType) -> [LTSectionModel]! { + fileprivate func sectionModelsByKey(_ key: LTType) -> [LTSectionModel]! { var result = [LTSectionModel]() - if let changes = fetchedResultsController.fetchedObjects as? [LTChangeModel] { + if let changes = fetchedResultsController.fetchedObjects { for changeModel in changes { createSectionByKey(changeModel, key: key) { (newsModel, sectionModel, finish) in if let newsModel = newsModel as LTNewsModel! { @@ -317,10 +317,10 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa return result } - private func createSectionByKey(changeModel: LTChangeModel, key: LTType, completionHandler:(newsModel: LTNewsModel?, sectionModel: LTSectionModel?, finish: Bool) -> Void) { + fileprivate func createSectionByKey(_ changeModel: LTChangeModel, key: LTType, completionHandler:(_ newsModel: LTNewsModel?, _ sectionModel: LTSectionModel?, _ finish: Bool) -> Void) { let bill = changeModel.law if bill.title == "" { - completionHandler(newsModel: nil, sectionModel: nil, finish: true) + completionHandler(nil, nil, true) return } @@ -330,7 +330,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa let bills = [bill] let sectionBillModel = LTSectionModel(entities: bills) sectionBillModel.addModel(newsModel) - completionHandler(newsModel: newsModel, sectionModel: sectionBillModel, finish: true) + completionHandler(newsModel, sectionBillModel, true) break @@ -342,7 +342,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa let sectionInitiatorModel = LTSectionModel(entities: initiators) sectionInitiatorModel.addModel(newsModel) - completionHandler(newsModel: newsModel, sectionModel: sectionInitiatorModel, finish: true) + completionHandler(newsModel, sectionInitiatorModel, true) break @@ -350,13 +350,13 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa let committees = [bill.committee] let sectionCommitteeModel = LTSectionModel(entities: committees) sectionCommitteeModel.addModel(newsModel) - completionHandler(newsModel: newsModel, sectionModel: sectionCommitteeModel, finish: true) + completionHandler(newsModel, sectionCommitteeModel, true) break } } - private func setArrayModel() { + fileprivate func setArrayModel() { fetchChanges {[unowned self] (finish) -> Void in if finish { self.arrayModelFromChanges() @@ -364,23 +364,23 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa } } - private func fetchChanges(completionHandler:(finish: Bool) -> Void) { - dispatch_async(CoreDataStackManager.coreDataQueue()) {[unowned self, weak fetchedResultsController = fetchedResultsController, weak loadingDate = loadingDate] in - if let loadingDate = loadingDate as NSDate! { - fetchedResultsController!.fetchRequest.predicate = NSPredicate(format: "date = %@", loadingDate.dateWithoutTime()) + fileprivate func fetchChanges(_ completionHandler:@escaping (_ finish: Bool) -> Void) { + CoreDataStackManager.coreDataQueue().async {[unowned self, weak fetchedResultsController = fetchedResultsController, loadingDate = loadingDate] in + if let loadingDate = loadingDate as Date! { + fetchedResultsController!.fetchRequest.predicate = NSPredicate(format: "date = %@", (loadingDate.dateWithoutTime() as NSDate)) do { try fetchedResultsController!.performFetch() } catch {} fetchedResultsController!.delegate = self - completionHandler(finish: true) + completionHandler(true) } } } //MARK: - NSFetchedResultsControllerDelegate - func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { + func controller(_ controller: NSFetchedResultsController, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { if nil == self.type { return } @@ -391,7 +391,7 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa if let sectionModel = sectionModel as LTSectionModel! { //apply filters for section model if needed if (arrayModel!.filtersApplied && sectionModel.filtersSet) || !arrayModel!.filtersApplied { - dispatch_async(dispatch_get_main_queue()) { + DispatchQueue.main.async { let existedSectionModel = arrayModel!.sectionWithEntities(sectionModel.entities) var row = 0 var section = 0 @@ -403,20 +403,20 @@ class LTMainContentViewController: UIViewController, UITableViewDataSource, UITa //insert row and section to tableView if arrayModel!.count() == section + 1 { - tableView!.insertSections(NSIndexSet(index: section), withRowAnimation: .Fade) - tableView!.insertRowsAtIndexPaths([NSIndexPath(forRow: row, inSection: section)], withRowAnimation: .Fade) + tableView!.insertSections(IndexSet(integer: section), with: .fade) + tableView!.insertRows(at: [IndexPath(row: row, section: section)], with: .fade) } } else { //add newsModel to existedSectionModel if nil == existedSectionModel!.newsModelWithEntity(newsModel.entity) { existedSectionModel!.addModel(newsModel) row = existedSectionModel!.count() - 1 - section = arrayModel!.changes.indexOf(existedSectionModel!)! + section = arrayModel!.changes.index(of: existedSectionModel!)! //insert row to tableView - let indexPath = NSIndexPath(forRow: row, inSection: section) + let indexPath = IndexPath(row: row, section: section) if arrayModel!.changes[section].count() == row + 1 { - tableView!.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) + tableView!.insertRows(at: [indexPath], with: .fade) } } } diff --git a/LawTracker/Sources/UI/MenuViewController/LTMenuDelegate.swift b/LawTracker/Sources/UI/MenuViewController/LTMenuDelegate.swift index bd70b42..af688a6 100644 --- a/LawTracker/Sources/UI/MenuViewController/LTMenuDelegate.swift +++ b/LawTracker/Sources/UI/MenuViewController/LTMenuDelegate.swift @@ -7,5 +7,5 @@ // protocol LTMenuDelegate { - func hideMenu(completionHandler: (finished: Bool) -> Void) + func hideMenu(_ completionHandler: @escaping (_ finished: Bool) -> Void) } diff --git a/LawTracker/Sources/UI/MenuViewController/LTMenuTableViewCell.swift b/LawTracker/Sources/UI/MenuViewController/LTMenuTableViewCell.swift index 714ba6c..30983df 100644 --- a/LawTracker/Sources/UI/MenuViewController/LTMenuTableViewCell.swift +++ b/LawTracker/Sources/UI/MenuViewController/LTMenuTableViewCell.swift @@ -12,11 +12,11 @@ class LTMenuTableViewCell: UITableViewCell { @IBOutlet var arrowImageView: UIImageView! @IBOutlet var titleLabel: UILabel! - override func setSelected(selected: Bool, animated: Bool) { + override func setSelected(_ selected: Bool, animated: Bool) { } - func fill(string: String) { + func fill(_ string: String) { titleLabel.text = string titleLabel.fit() } diff --git a/LawTracker/Sources/UI/MenuViewController/LTMenuViewController.swift b/LawTracker/Sources/UI/MenuViewController/LTMenuViewController.swift index d084835..5b85343 100644 --- a/LawTracker/Sources/UI/MenuViewController/LTMenuViewController.swift +++ b/LawTracker/Sources/UI/MenuViewController/LTMenuViewController.swift @@ -11,22 +11,22 @@ import UIKit let kLTChesnoURL = "http://www.chesno.org" enum LTMenuCells: Int { - case Manual = 0, - WebSite = 1 + case manual = 0, + webSite = 1 - static let cellTypes = [Manual, WebSite] + static let cellTypes = [manual, webSite] }; class LTMenuViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var menuDelegate: LTMenuDelegate? //MARK: - UITableViewDataSource methods - func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return LTMenuCells.cellTypes.count } - func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { - let cell = tableView.dequeueReusableCellWithIdentifier("LTMenuTableViewCell", forIndexPath: indexPath) as! LTMenuTableViewCell + func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { + let cell = tableView.dequeueReusableCell(withIdentifier: "LTMenuTableViewCell", for: indexPath) as! LTMenuTableViewCell var string = "" switch indexPath.row { case 0: @@ -46,23 +46,23 @@ class LTMenuViewController: UIViewController, UITableViewDataSource, UITableView return cell } - func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { + func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let menuDelegate = menuDelegate { menuDelegate.hideMenu() {[weak storyboard = self.storyboard, weak navigationController = navigationController] (finished) in if finished { switch indexPath.row { case 0: - dispatch_async(dispatch_get_main_queue()) { - let helpViewController = storyboard!.instantiateViewControllerWithIdentifier("LTHelpController") as! LTHelpController - navigationController!.presentViewController(helpViewController, animated: true, completion: nil) + DispatchQueue.main.async { + let helpViewController = storyboard!.instantiateViewController(withIdentifier: "LTHelpController") as! LTHelpController + navigationController!.present(helpViewController, animated: true, completion: nil) //navigationController!.pushViewController(helpViewController, animated: true) } break case 1: - let url = NSURL(string: kLTChesnoURL) - let app = UIApplication.sharedApplication() + let url = URL(string: kLTChesnoURL) + let app = UIApplication.shared if app.canOpenURL(url!) { app.openURL(url!) } diff --git a/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedRootView.swift b/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedRootView.swift index f57c1ce..26510f4 100644 --- a/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedRootView.swift +++ b/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedRootView.swift @@ -41,8 +41,8 @@ class LTNewsFeedRootView: OTMView { override func awakeFromNib() { super.awakeFromNib() - datePicker.date = NSDate().previousDay() - datePicker.maximumDate = NSDate() + datePicker.date = Date().previousDay() + datePicker.maximumDate = Date() selectedButton = byCommitteesButton if let label = searchDateButton.titleLabel { @@ -52,54 +52,54 @@ class LTNewsFeedRootView: OTMView { func showMenu() { //horizontal - let width = CGRectGetWidth(menuContainerView.frame) < 250.0 ? CGRectGetWidth(menuContainerView.frame) : 250.0; + let width = menuContainerView.frame.width < 250.0 ? menuContainerView.frame.width : 250.0; animateMenu(width, show: !menuShown) } - func hideMenu(completionHandler: (finished: Bool) -> Void) { + func hideMenu(_ completionHandler: @escaping (_ finished: Bool) -> Void) { if menuShown { - let width = CGRectGetWidth(menuContainerView.frame) < 250.0 ? CGRectGetWidth(menuContainerView.frame) : 250.0; + let width = menuContainerView.frame.width < 250.0 ? menuContainerView.frame.width : 250.0; let menuContainer = menuContainerView - UIView.animateWithDuration(0.4, animations: { - var center = menuContainer.center - center.x = -width / 2.0 - menuContainer.center = center + UIView.animate(withDuration: 0.4, animations: { + var center = menuContainer?.center + center?.x = -width / 2.0 + menuContainer?.center = center! self.dismissChildControllersButton.alpha = 0.0 }, completion: {(finished: Bool) -> Void in self.menuShown = !self.menuShown - completionHandler(finished: finished) + completionHandler(finished) }) } } func showDatePicker() { - datePickerContainer.hidden = false + datePickerContainer.isHidden = false datePickerShown = true } func hideDatePicker() { - datePickerContainer.hidden = true + datePickerContainer.isHidden = true datePickerShown = false } - func fillSearchButton(date: NSDate) { - dispatch_async(dispatch_get_main_queue()) { - self.searchDateButton.setTitle(date.longString(), forState: .Normal) + func fillSearchButton(_ date: Date) { + DispatchQueue.main.async { + self.searchDateButton.setTitle(date.longString(), for: UIControlState()) self.datePicker.date = date } } - private func animateMenu(width: CGFloat, show: Bool) { + fileprivate func animateMenu(_ width: CGFloat, show: Bool) { let menuContainer = menuContainerView if show { hideDatePicker() } - UIView.animateWithDuration(0.4, animations: { - var center = menuContainer.center - center.x = show ? width / 2.0 : -width / 2.0 - menuContainer.center = center + UIView.animate(withDuration: 0.4, animations: { + var center = menuContainer?.center + center?.x = show ? width / 2.0 : -width / 2.0 + menuContainer?.center = center! self.dismissChildControllersButton.alpha = show ? 0.8 : 0.0 }, completion: {(finished: Bool) -> Void in self.menuShown = !self.menuShown diff --git a/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedViewController.swift b/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedViewController.swift index 1297a7a..1b5605f 100644 --- a/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedViewController.swift +++ b/LawTracker/Sources/UI/NewsFeedViewController/LTNewsFeedViewController.swift @@ -15,7 +15,7 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate var currentController : LTMainContentViewController? var destinationController : LTMainContentViewController? var animator : LTSliderAnimator? - var shownDate : NSDate? + var shownDate : Date? var dateIsChoosenFromPicker : Bool = false var isLoading : Bool = false @@ -34,18 +34,18 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - var minDate : NSDate { + var minDate : Date { get { - let dateFormatter = NSDateFormatter() + let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd" - return dateFormatter.dateFromString("2000-01-01")! + return dateFormatter.date(from: "2000-01-01")! } } var menuViewController: LTMenuViewController { get { - let menuViewController = self.storyboard!.instantiateViewControllerWithIdentifier("LTMenuViewController") as! LTMenuViewController + let menuViewController = self.storyboard!.instantiateViewController(withIdentifier: "LTMenuViewController") as! LTMenuViewController menuViewController.menuDelegate = self return menuViewController @@ -54,7 +54,7 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate var rootView : LTNewsFeedRootView? { get { - if isViewLoaded() && view.isKindOfClass(LTNewsFeedRootView) { + if isViewLoaded && view.isKind(of: LTNewsFeedRootView.self) { return view as? LTNewsFeedRootView } else { return nil @@ -72,11 +72,11 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate setupContent() - let date = NSDate().previousDay() + let date = Date().previousDay() rootView!.fillSearchButton(date) //observe internet connection - NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("networkStatusChanged:"), name: ReachabilityStatusChangedNotification, object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(LTNewsFeedViewController.networkStatusChanged(_:)), name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil) Reach().monitorReachabilityChanges() let settingsModel = VTSettingModel() @@ -117,59 +117,59 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate addChildViewControllerInView(menuViewController, view: rootView!.menuContainerView) } - override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { - super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) + override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { + super.viewWillTransition(to: size, with: coordinator) - coordinator.animateAlongsideTransition({[weak rootView = rootView] (UIViewControllerTransitionCoordinatorContext) -> Void in + coordinator.animate(alongsideTransition: {[weak rootView = rootView] (UIViewControllerTransitionCoordinatorContext) -> Void in if rootView!.menuShown { rootView!.showMenu() }}, completion: {(UIViewControllerTransitionCoordinatorContext) -> Void in }) } - override func preferredStatusBarStyle() -> UIStatusBarStyle { - return .LightContent + override var preferredStatusBarStyle : UIStatusBarStyle { + return .lightContent } - override func viewWillAppear(animated: Bool) { + override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) - NSNotificationCenter.defaultCenter().addObserver(self, selector: "loadChangesForAnotherDate:", name: "loadChangesForAnotherDate", object: nil) + NotificationCenter.default.addObserver(self, selector: #selector(LTNewsFeedViewController.loadChangesForAnotherDate(_:)), name: NSNotification.Name(rawValue: "loadChangesForAnotherDate"), object: nil) } - override func viewWillDisappear(animated: Bool) { + override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) - NSNotificationCenter.defaultCenter().removeObserver(self, name: "loadChangesForAnotherDate", object: nil) + NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "loadChangesForAnotherDate"), object: nil) } - func networkStatusChanged(notification: NSNotification) { + func networkStatusChanged(_ notification: Notification) { let userInfo = notification.userInfo - print(userInfo) + print(userInfo ?? "nil") } //MARK: - Interface Handling - @IBAction func onGesture(sender: LTPanGestureRacognizer) { + @IBAction func onGesture(_ sender: LTPanGestureRacognizer) { let direction = sender.direction - if direction != .Right { + if direction != .right { handlePageSwitchingGesture(sender) } } - @IBAction func onDismissFilterViewButton(sender: UIButton) { - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + @IBAction func onDismissFilterViewButton(_ sender: UIButton) { + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.hideMenu() {finished in} } } - @IBAction func onMenuButton(sender: AnyObject) { - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + @IBAction func onMenuButton(_ sender: AnyObject) { + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.showMenu() } } - @IBAction func onFilterButton(sender: UIButton) { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak storyboard = storyboard, weak rootView = rootView] in - let filterController = storyboard!.instantiateViewControllerWithIdentifier("LTFilterViewController") as! LTFilterViewController + @IBAction func onFilterButton(_ sender: UIButton) { + DispatchQueue.main.async {[unowned self, weak storyboard = storyboard, weak rootView = rootView] in + let filterController = storyboard!.instantiateViewController(withIdentifier: "LTFilterViewController") as! LTFilterViewController filterController.type = self.filterType filterController.filterDelegate = self @@ -189,15 +189,15 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate break } - dispatch_async(CoreDataStackManager.coreDataQueue()) {[unowned self] in - let arrayModel = LTArrayModel(entityName: entityName, predicate: NSPredicate(value: true), date: NSDate()) + CoreDataStackManager.coreDataQueue().async {[unowned self] in + let arrayModel = LTArrayModel(entityName: entityName, predicate: NSPredicate(value: true), date: Date()) rootView!.showLoadingViewInViewWithMessage(rootView!.contentView, message: "Завантаження фільтрів...") arrayModel.filters(self.filterType, completionHandler: { (result, finish) -> Void in if finish { rootView!.hideLoadingView() - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + DispatchQueue.main.async {[unowned self] in filterController.filters = result - self.presentViewController(filterController, animated: true, completion: nil) + self.present(filterController, animated: true, completion: nil) } } }) @@ -206,8 +206,8 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - @IBAction func onByCommitteesButton(sender: LTSwitchButton) { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView] in + @IBAction func onByCommitteesButton(_ sender: LTSwitchButton) { + DispatchQueue.main.async {[unowned self, weak rootView = rootView] in if rootView!.selectedButton != sender { self.scrollToTop() rootView!.selectedButton = sender @@ -216,8 +216,8 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - @IBAction func onByInitializersButton(sender: LTSwitchButton) { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView] in + @IBAction func onByInitializersButton(_ sender: LTSwitchButton) { + DispatchQueue.main.async {[unowned self, weak rootView = rootView] in if rootView!.selectedButton != sender { self.scrollToTop() rootView!.selectedButton = sender @@ -226,8 +226,8 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - @IBAction func byLawsButton(sender: LTSwitchButton) { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView] in + @IBAction func byLawsButton(_ sender: LTSwitchButton) { + DispatchQueue.main.async {[unowned self, weak rootView = rootView] in self.scrollToTop() if rootView!.selectedButton != sender { self.scrollToTop() @@ -237,27 +237,27 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - @IBAction func onSearchButton(sender: AnyObject) { - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + @IBAction func onSearchButton(_ sender: AnyObject) { + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.showDatePicker() } } - @IBAction func onHidePickerButton(sender: AnyObject) { - dispatch_async(dispatch_get_main_queue()) {[weak rootView = rootView] in + @IBAction func onHidePickerButton(_ sender: AnyObject) { + DispatchQueue.main.async {[weak rootView = rootView] in rootView!.hideDatePicker() } } - @IBAction func onDonePickerButton(sender: AnyObject) { + @IBAction func onDonePickerButton(_ sender: AnyObject) { let client = LTClient.sharedInstance() - if let task = client.downloadTask as NSURLSessionDataTask! { + if let task = client.downloadTask as URLSessionDataTask! { task.cancel() } isLoading = false - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak rootView = rootView, weak destinationController = destinationController, weak currentController = currentController] in + DispatchQueue.main.async {[unowned self, weak rootView = rootView, weak destinationController = destinationController, weak currentController = currentController] in rootView!.hideDatePicker() if self.isLoading { @@ -280,12 +280,12 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } func refreshData() { - dispatch_async(dispatch_get_main_queue()) {[unowned self, weak date = rootView!.datePicker.date, weak destinationController = destinationController, weak currentController = currentController] in - let alertViewController: UIAlertController = UIAlertController(title: "Оновити базу законопроектів, ініціаторів та комітетів?", message:"Це може зайняти кілька хвилин", preferredStyle: .Alert) - alertViewController.addAction(UIAlertAction(title: "Так", style: .Default, handler: {(UIAlertAction) in + DispatchQueue.main.async {[unowned self, date = rootView!.datePicker.date, weak destinationController = destinationController, weak currentController = currentController] in + let alertViewController: UIAlertController = UIAlertController(title: "Оновити базу законопроектів, ініціаторів та комітетів?", message:"Це може зайняти кілька хвилин", preferredStyle: .alert) + alertViewController.addAction(UIAlertAction(title: "Так", style: .default, handler: {(UIAlertAction) in self.loadData({(finish, success) -> Void in if success { - self.downloadChanges(date!, choosenInPicker: false, completionHandler: {(finish, success) -> Void in + self.downloadChanges(date, choosenInPicker: false, completionHandler: {(finish, success) -> Void in if success { if let destinationController = destinationController as LTMainContentViewController! { destinationController.loadingDate = date @@ -298,18 +298,18 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate }) })) - alertViewController.addAction(UIAlertAction(title: "Ні", style: .Default, handler: nil)) + alertViewController.addAction(UIAlertAction(title: "Ні", style: .default, handler: nil)) - self.presentViewController(alertViewController, animated: true, completion: nil) + self.present(alertViewController, animated: true, completion: nil) } } // MARK: - UIGestureRecognizerDelegate - func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWithGestureRecognizer otherGestureRecognizer: UIGestureRecognizer) -> Bool { + func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return navigationGesture == gestureRecognizer || navigationGesture == otherGestureRecognizer } - func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool { + func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool { if isLoading { return false } @@ -332,7 +332,7 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate var isNavigationGesture = false if let gestureRecognizer = navigationGesture as LTPanGestureRacognizer! { let direction = gestureRecognizer.direction - isNavigationGesture = .Right == direction + isNavigationGesture = .right == direction } if shouldPop && isNavigationGesture { @@ -344,17 +344,17 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } let tableView = currentController!.rootView!.contentTableView - let bounds = tableView.bounds + let bounds = tableView?.bounds let dateInPicker = rootView!.datePicker.date - let shouldAnimateToTop = (CGRectGetMinY(bounds) <= 0 && .Down == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(NSDate().dateWithoutTime()) == .OrderedAscending) - let shouldAnimateToBottom = ((CGRectGetMaxY(bounds) >= (tableView.contentSize.height - 1)) && .Up == navigationGesture.direction) + let shouldAnimateToTop = (bounds!.minY <= 0 && .down == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(Date().dateWithoutTime()) == .orderedAscending) + let shouldAnimateToBottom = ((bounds!.maxY >= (tableView!.contentSize.height - 1)) && .up == navigationGesture.direction) let shouldBegin = shouldAnimateToTop || shouldAnimateToBottom - if !shouldBegin && (CGRectGetMinY(bounds) <= 0 && .Down == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(NSDate().dateWithoutTime()) == .OrderedSame) { + if !shouldBegin && (bounds!.minY <= 0 && .down == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(Date().dateWithoutTime()) == .orderedSame) { refreshData() } - if (.Up == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(minDate) == .OrderedSame) { + if (.up == navigationGesture.direction && dateInPicker.dateWithoutTime().compare(minDate) == .orderedSame) { return false } @@ -367,9 +367,9 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate // MARK: - Public func setupContent() { if let rootView = rootView as LTNewsFeedRootView! { - currentController = storyboard!.instantiateViewControllerWithIdentifier("LTMainContentViewController") as? LTMainContentViewController + currentController = storyboard!.instantiateViewController(withIdentifier: "LTMainContentViewController") as? LTMainContentViewController let containerView = rootView.contentView - addChildViewControllerInView(currentController!, view: containerView) + addChildViewControllerInView(currentController!, view: containerView!) setCurrentController(currentController!, animated: false, forwardDirection: false) scrollToTop() @@ -377,49 +377,49 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } // MARK: - Private - private func scrollToTop() { + fileprivate func scrollToTop() { if let currentController = currentController as LTMainContentViewController! { if let currentControllerView = currentController.rootView as LTMainContentRootView! { - currentControllerView.contentTableView.setContentOffset(CGPointZero, animated: false) + currentControllerView.contentTableView.setContentOffset(CGPoint.zero, animated: false) } } else if let destinationController = destinationController as LTMainContentViewController! { if let destinationControllerView = destinationController.rootView as LTMainContentRootView! { - destinationControllerView.contentTableView.setContentOffset(CGPointZero, animated: false) + destinationControllerView.contentTableView.setContentOffset(CGPoint.zero, animated: false) } } } - private func handlePageSwitchingGesture(recognizer: LTPanGestureRacognizer) { + fileprivate func handlePageSwitchingGesture(_ recognizer: LTPanGestureRacognizer) { if nil == rootView { return } let recognizerView = recognizer.view - let location = recognizer.locationInView(recognizerView) + let location = recognizer.location(in: recognizerView) let direction = recognizer.direction - let translation = recognizer.translationInView(recognizerView) + let translation = recognizer.translation(in: recognizerView) let state = recognizer.state - if .Changed == state { + if .changed == state { let dx = recognizer.startLocation.x - location.x let dy = recognizer.startLocation.y - location.y let distance = sqrt(dx*dx + dy*dy) if distance >= 0.0 { if let animator = animator as LTSliderAnimator! { - let percent = (.Down == direction && location.y < recognizer.startLocation.y) || (.Up == direction && location.y > recognizer.startLocation.y) ? 0.0 : fabs(distance/CGRectGetHeight(recognizerView!.bounds)) + let percent = (.down == direction && location.y < recognizer.startLocation.y) || (.up == direction && location.y > recognizer.startLocation.y) ? 0.0 : fabs(distance/recognizerView!.bounds.height) animator.updateInteractiveTransition(percent) } else { animator = LTSliderAnimator() //instantiate LTMainContentViewController with LTChangesModel - let nextController = storyboard!.instantiateViewControllerWithIdentifier("LTMainContentViewController") as! LTMainContentViewController - setCurrentController(nextController, animated: true, forwardDirection: .Up == direction) + let nextController = storyboard!.instantiateViewController(withIdentifier: "LTMainContentViewController") as! LTMainContentViewController + setCurrentController(nextController, animated: true, forwardDirection: .up == direction) let dateInPicker = rootView!.datePicker.date - if .Down == direction && translation.y > 0 { - if dateInPicker.compare(NSDate()) == .OrderedAscending { + if .down == direction && translation.y > 0 { + if dateInPicker.compare(Date()) == .orderedAscending { let date = dateInPicker.nextDay() downloadChanges(date, choosenInPicker: false, completionHandler: {[weak destinationController = destinationController, weak currentController = currentController] (finish, success) -> Void in if success { @@ -449,41 +449,41 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } } - } else if .Ended == state { - let velocity = recognizer.velocityInView(recognizerView) - if (velocity.y > 0 && .Down == direction) || (velocity.y < 0 && .Up == direction) { + } else if .ended == state { + let velocity = recognizer.velocity(in: recognizerView) + if (velocity.y > 0 && .down == direction) || (velocity.y < 0 && .up == direction) { scrollToTop() animator?.finishInteractiveTransition() } else { animator?.cancelInteractiveTransition() } - } else if .Cancelled == state { + } else if .cancelled == state { animator?.cancelInteractiveTransition() } - if .Cancelled == state || .Ended == state { + if .cancelled == state || .ended == state { animator = nil } } - func setCurrentController(controller: LTMainContentViewController, animated: Bool, forwardDirection: Bool) { + func setCurrentController(_ controller: LTMainContentViewController, animated: Bool, forwardDirection: Bool) { if currentController != controller { destinationController = controller transitionFromViewController(currentController, toViewController: controller, animated: animated, forward: forwardDirection) } } - func transitionFromViewController(fromViewController: LTMainContentViewController?, toViewController: LTMainContentViewController, animated: Bool, forward: Bool) { - if false == isViewLoaded() { + func transitionFromViewController(_ fromViewController: LTMainContentViewController?, toViewController: LTMainContentViewController, animated: Bool, forward: Bool) { + if false == isViewLoaded { return } let containerView = rootView!.contentView toViewController.view.translatesAutoresizingMaskIntoConstraints = true - toViewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] + toViewController.view.autoresizingMask = [.flexibleWidth, .flexibleHeight] - addChildViewControllerInView(toViewController, view:containerView) + addChildViewControllerInView(toViewController, view:containerView!) if nil == fromViewController { commitFeedController(toViewController) @@ -491,40 +491,40 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate return } - let context = LTTransitionContext(source: fromViewController, destination: toViewController, containerView: containerView, animated: animated, forward: forward) + let context = LTTransitionContext(source: fromViewController, destination: toViewController, containerView: containerView!, animated: animated, forward: forward) context.animator = animator - let interactiveFeedScrollController = false == context.isInteractive() ? LTSliderAnimator() : animator + let interactiveFeedScrollController = false == context.isInteractive ? LTSliderAnimator() : animator if let interactiveFeedScrollController = interactiveFeedScrollController as LTSliderAnimator! { - interactiveFeedScrollController.operation = forward ? .Pop : .Push + interactiveFeedScrollController.operation = forward ? .pop : .push interactiveFeedScrollController.duration = 0.5 context.completionBlock = {[unowned self] (complete) in if true == complete { self.commitFeedController(toViewController) } else { toViewController.view.removeFromSuperview() - fromViewController!.view.frame = containerView.bounds + fromViewController!.view.frame = (containerView?.bounds)! self.currentController = fromViewController self.destinationController = nil } interactiveFeedScrollController.animationEnded(complete) - containerView.userInteractionEnabled = true + containerView?.isUserInteractionEnabled = true } - containerView.userInteractionEnabled = false + containerView?.isUserInteractionEnabled = false - if context.isInteractive() { + if context.isInteractive { if let _ = animator as LTSliderAnimator! { context.animator!.startInteractiveTransition(context) } } else { - interactiveFeedScrollController.animateTransition(context) + interactiveFeedScrollController.animateTransition(using: context) } } } - func commitFeedController(feedController: LTMainContentViewController) { + func commitFeedController(_ feedController: LTMainContentViewController) { //remove rootView of previous currentController from superview if currentController != feedController { if nil != currentController { @@ -533,23 +533,23 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate currentController = feedController destinationController = nil - feedController.didMoveToParentViewController(self) + feedController.didMove(toParentViewController: self) } } - private func downloadChanges(date: NSDate, choosenInPicker: Bool, completionHandler:(finish: Bool, success: Bool) -> Void) { + fileprivate func downloadChanges(_ date: Date, choosenInPicker: Bool, completionHandler:@escaping (_ finish: Bool, _ success: Bool) -> Void) { let status = Reach().connectionStatus() switch status { - case .Unknown, .Offline: + case .unknown, .offline: let userInfo = [NSLocalizedDescriptionKey : "Немає доступу до Інтернету."] let error = NSError(domain: "ConnectionError", code: -1009, userInfo: userInfo) processError(error){[unowned self] (void) in self.downloadChanges(date, choosenInPicker: choosenInPicker, completionHandler: completionHandler) } - completionHandler(finish: true, success: false) + completionHandler(true, false) self.isLoading = false return @@ -563,10 +563,10 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate rootView.fillSearchButton(date) dateIsChoosenFromPicker = choosenInPicker - dispatch_async(CoreDataStackManager.coreDataQueue()) {[unowned self, weak rootView = rootView] in + CoreDataStackManager.coreDataQueue().async {[unowned self, weak rootView = rootView] in if let changes = LTChangeModel.changesForDate(date) as [LTChangeModel]! { if changes.count > 0 { - completionHandler(finish: true, success: true) + completionHandler(true, true) self.isLoading = false return } @@ -582,13 +582,13 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate settingsModel.firstLaunch = true settingsModel.lastDownloadDate = date - completionHandler(finish: true, success: success) + completionHandler(true, success) } else { self.processError(error!){[unowned self] (void) in self.downloadChanges(date, choosenInPicker: choosenInPicker, completionHandler: completionHandler) } - completionHandler(finish: true, success: success) + completionHandler(true, success) self.isLoading = false } } @@ -596,7 +596,7 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } } - private func loadData(completionHandler:(finish: Bool, success: Bool) -> Void) { + fileprivate func loadData(_ completionHandler:@escaping (_ finish: Bool, _ success: Bool) -> Void) { if nil == rootView { return } @@ -604,14 +604,14 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate let status = Reach().connectionStatus() switch status { - case .Unknown, .Offline: + case .unknown, .offline: let userInfo = [NSLocalizedDescriptionKey : "Немає доступу до Інтернету."] let error = NSError(domain: "ConnectionError", code: -1009, userInfo: userInfo) processError(error){[unowned self] (void) in self.loadData(completionHandler) } - completionHandler(finish: true, success: false) + completionHandler(true, false) self.isLoading = false return @@ -644,37 +644,37 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate self.isLoading = false if success { rootView!.hideLoadingView() - completionHandler(finish: true, success: true) + completionHandler(true, true) } else { - completionHandler(finish: true, success: false) + completionHandler(true, false) self.processError(error!){[unowned self] void in self.loadData(completionHandler) } } }) } else { - completionHandler(finish: true, success: false) + completionHandler(true, false) self.processError(error!){[unowned self] void in self.loadData(completionHandler) } } }) } else { - completionHandler(finish: true, success: false) + completionHandler(true, false) self.processError(error!){[unowned self] void in self.loadData(completionHandler) } } }) } else { - completionHandler(finish: true, success: false) + completionHandler(true, false) self.processError(error!){[unowned self] void in self.loadData(completionHandler) } } }) } else { - completionHandler(finish: true, success: false) + completionHandler(true, false) self.processError(error!){[unowned self] void in self.loadData(completionHandler) } @@ -682,7 +682,7 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate }) } - private func processError(error:NSError, completionHandler:(UIAlertAction) -> Void) { + fileprivate func processError(_ error:NSError, completionHandler:@escaping (UIAlertAction) -> Void) { rootView!.hideLoadingView() isLoading = false var title = String() @@ -737,27 +737,27 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate break } - dispatch_async(dispatch_get_main_queue()) {[unowned self] in - let alertViewController: UIAlertController = UIAlertController(title: title, message: "Повторити спробу завантаження?", preferredStyle: .Alert) - alertViewController.addAction(UIAlertAction(title: "Так", style: .Default, handler: completionHandler)) + DispatchQueue.main.async {[unowned self] in + let alertViewController: UIAlertController = UIAlertController(title: title, message: "Повторити спробу завантаження?", preferredStyle: .alert) + alertViewController.addAction(UIAlertAction(title: "Так", style: .default, handler: completionHandler)) - alertViewController.addAction(UIAlertAction(title: "Ні", style: .Default, handler: nil)) + alertViewController.addAction(UIAlertAction(title: "Ні", style: .default, handler: nil)) - self.presentViewController(alertViewController, animated: true, completion: nil) + self.present(alertViewController, animated: true, completion: nil) } } //MARK: - LTMenuDelegate methods - func hideMenu(completionHandler: (finished: Bool) -> Void) { + func hideMenu(_ completionHandler: @escaping (_ finished: Bool) -> Void) { if let rootView = rootView { rootView.hideMenu({ (finished) -> Void in - completionHandler(finished: finished) + completionHandler(finished) }) return } - completionHandler(finished: false) + completionHandler(false) } //MARK: - LTFilterDelegate methods @@ -773,22 +773,22 @@ class LTNewsFeedViewController: UIViewController, UINavigationControllerDelegate } //MARK: - NSNotificationCenter - func loadChangesForAnotherDate(notification: NSNotification) { + func loadChangesForAnotherDate(_ notification: Notification) { isLoading = false if nil == rootView { return } - let date = nil == shownDate ? NSDate().previousDay() : shownDate + let date = nil == shownDate ? Date().previousDay() : shownDate if let userInfo = notification.userInfo as NSDictionary! { let dateInPicker = rootView!.datePicker.date if let needLoadChangesForAnotherDate = userInfo["needLoadChangesForAnotherDay"] as? Bool { if needLoadChangesForAnotherDate { - if !dateIsChoosenFromPicker && (dateInPicker.compare(NSDate().dateWithoutTime()) != .OrderedSame) && (loadingCount < kLTMaxLoadingCount) && dateInPicker.compare(minDate) != .OrderedSame { + if !dateIsChoosenFromPicker && (dateInPicker.compare(Date().dateWithoutTime()) != .orderedSame) && (loadingCount < kLTMaxLoadingCount) && dateInPicker.compare(minDate) != .orderedSame { loadingCount += 1 var newDate = date - if date!.dateWithoutTime().compare(dateInPicker.dateWithoutTime()) == .OrderedAscending { + if date!.dateWithoutTime().compare(dateInPicker.dateWithoutTime()) == .orderedAscending { newDate = dateInPicker.nextDay() } else { newDate = dateInPicker.previousDay() diff --git a/LawTracker/Sources/UI/NewsFeedViewController/LTSliderAnimator.swift b/LawTracker/Sources/UI/NewsFeedViewController/LTSliderAnimator.swift index 280097d..1f32469 100644 --- a/LawTracker/Sources/UI/NewsFeedViewController/LTSliderAnimator.swift +++ b/LawTracker/Sources/UI/NewsFeedViewController/LTSliderAnimator.swift @@ -10,7 +10,7 @@ import UIKit class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerInteractiveTransitioning { var operation : UINavigationControllerOperation! - var duration : NSTimeInterval = 0.2 + var duration : TimeInterval = 0.2 internal var shadowView : UIView? internal weak var destination : UIViewController! @@ -18,20 +18,20 @@ class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewC internal var curve : UIViewAnimationCurve { get { - return .EaseInOut + return .easeInOut } } internal var transitionContext : LTTransitionContext! - internal var timeInterval : NSTimeInterval! + internal var timeInterval : TimeInterval! internal var interacting : Bool! // MARK: - Public - func updateInteractiveTransition(percentComplete: CGFloat) { + func updateInteractiveTransition(_ percentComplete: CGFloat) { let percent = max(0.0, min(1.0, percentComplete)) - timeInterval = duration * NSTimeInterval(percent) + timeInterval = duration * TimeInterval(percent) transitionContext.updateInteractiveTransition(percent) contextChangedPercentComplete(transitionContext, percentComplete: percent, completionHandler: nil) @@ -46,7 +46,7 @@ class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewC contextChangedPercentComplete(transitionContext, percentComplete: percentComplete) {completed in let context = self.transitionContext - context.completeTransition(!context.transitionWasCancelled()) + context?.completeTransition(context!.transitionWasCancelled) } } @@ -59,83 +59,82 @@ class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewC contextChangedPercentComplete(transitionContext, percentComplete: percentComplete) {completed in let context = self.transitionContext - context.completeTransition(!context.transitionWasCancelled()) + context?.completeTransition(context!.transitionWasCancelled) } } // MARK: - Private - func prepareAnimationForTransition(transitionContext: LTTransitionContext) { - if let bounds = transitionContext.containerView()?.bounds as CGRect! { + func prepareAnimationForTransition(_ transitionContext: LTTransitionContext) { + if let bounds = transitionContext.containerView.bounds as CGRect! { let shadow = UIView(frame: bounds) - shadow.backgroundColor = UIColor.blackColor() + shadow.backgroundColor = UIColor.black shadowView = shadow } - if let destinationController = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as UIViewController! { + if let destinationController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to) as UIViewController! { let destinationView = destinationController.view - destinationView.frame = transitionContext.initialFrameForViewController(destinationController) + destinationView?.frame = transitionContext.initialFrame(for: destinationController) destination = destinationController } - if let sourceController = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as UIViewController! { + if let sourceController = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from) as UIViewController! { let sourceView = sourceController.view - sourceView.frame = transitionContext.initialFrameForViewController(sourceController) + sourceView?.frame = transitionContext.initialFrame(for: sourceController) source = sourceController } - - if let containerView = transitionContext.containerView() as UIView! { - if .Push == operation { - containerView.insertSubview(destination.view, aboveSubview: source.view) - if let shadowView = shadowView as UIView! { - containerView.insertSubview(shadowView, aboveSubview: source.view) - shadowView.alpha = 0.0 - } - } else if .Pop == operation { - containerView.insertSubview(destination.view, belowSubview: source.view) - if let shadowView = shadowView as UIView! { - containerView.insertSubview(shadowView, belowSubview: source.view) - shadowView.alpha = 1.0 - } + + let containerView = transitionContext.containerView + if .push == operation { + containerView.insertSubview(destination.view, aboveSubview: source.view) + if let shadowView = shadowView as UIView! { + containerView.insertSubview(shadowView, aboveSubview: source.view) + shadowView.alpha = 0.0 + } + } else if .pop == operation { + containerView.insertSubview(destination.view, belowSubview: source.view) + if let shadowView = shadowView as UIView! { + containerView.insertSubview(shadowView, belowSubview: source.view) + shadowView.alpha = 1.0 } } } - func contextChangedPercentComplete(transitionContext: LTTransitionContext, percentComplete: CGFloat, completionHandler:LTCompletionBlock?) { - let duration = (transitionContext.isInteractive()) && (true == interacting) && (0 != timeInterval) ? 0 : transitionDuration(transitionContext) - timeInterval - var options : UIViewAnimationOptions = .BeginFromCurrentState + func contextChangedPercentComplete(_ transitionContext: LTTransitionContext, percentComplete: CGFloat, completionHandler:LTCompletionBlock?) { + let duration = (transitionContext.isInteractive) && (true == interacting) && (0 != timeInterval) ? 0 : transitionDuration(using: transitionContext) - timeInterval + var options : UIViewAnimationOptions = .beginFromCurrentState - if .EaseInOut == curve { - if .EaseIn == curve { - options = options.union(.CurveEaseIn) - } else if .EaseOut == curve { - options = options.union(.CurveEaseOut) + if .easeInOut == curve { + if .easeIn == curve { + options = options.union(.curveEaseIn) + } else if .easeOut == curve { + options = options.union(.curveEaseOut) } else { - options = [.CurveLinear, .BeginFromCurrentState] + options = [.curveLinear, .beginFromCurrentState] } } - UIView.animateWithDuration(duration, delay: 0, options: options, animations: { - self.destination.view.frame = transitionContext.finalFrameForViewController(self.destination) - self.source.view.frame = transitionContext.finalFrameForViewController(self.source) + UIView.animate(withDuration: duration, delay: 0, options: options, animations: { + self.destination.view.frame = transitionContext.finalFrame(for: self.destination) + self.source.view.frame = transitionContext.finalFrame(for: self.source) if let shadowView = self.shadowView as UIView! { - shadowView.alpha = .Push == self.operation ? percentComplete : 1.0 - percentComplete + shadowView.alpha = .push == self.operation ? percentComplete : 1.0 - percentComplete } }, completion: completionHandler) } //MARK: - UIViewControllerAnimatedTransitioning - func completionSpeed() -> CGFloat { + var completionSpeed : CGFloat { return 1.0 } - func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval { - let duration = self.duration / NSTimeInterval(completionSpeed()); + func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { + let duration = self.duration / TimeInterval(completionSpeed); if let transitionContext = transitionContext as UIViewControllerContextTransitioning! { - if transitionContext.isAnimated() && false == transitionContext.transitionWasCancelled() { + if transitionContext.isAnimated && false == transitionContext.transitionWasCancelled { return duration } } @@ -143,16 +142,16 @@ class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewC return 0.0 } - func animateTransition(transitionContext: UIViewControllerContextTransitioning) { + func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if let context = transitionContext as? LTTransitionContext { prepareAnimationForTransition(context) contextChangedPercentComplete(context, percentComplete: 1.0) {complete in - context.completeTransition(!context.transitionWasCancelled()) + context.completeTransition(context.transitionWasCancelled) } } } - func animationEnded(transitionCompleted: Bool) { + func animationEnded(_ transitionCompleted: Bool) { if let shadowView = shadowView as UIView! { shadowView.removeFromSuperview() } @@ -161,7 +160,7 @@ class LTSliderAnimator: NSObject, UIViewControllerAnimatedTransitioning, UIViewC } //MARK: - UIViewControllerInteractiveTransitioning - func startInteractiveTransition(transitionContext: UIViewControllerContextTransitioning) { + func startInteractiveTransition(_ transitionContext: UIViewControllerContextTransitioning) { if let context = transitionContext as? LTTransitionContext { self.transitionContext = context interacting = true diff --git a/LawTracker/Sources/UI/NewsFeedViewController/LTTransitionContext.swift b/LawTracker/Sources/UI/NewsFeedViewController/LTTransitionContext.swift index ab14a76..d59a895 100644 --- a/LawTracker/Sources/UI/NewsFeedViewController/LTTransitionContext.swift +++ b/LawTracker/Sources/UI/NewsFeedViewController/LTTransitionContext.swift @@ -8,15 +8,16 @@ import UIKit -typealias LTCompletionBlock = (complete: Bool!) -> Void +typealias LTCompletionBlock = (_ complete: Bool) -> Void class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { + var completionBlock : LTCompletionBlock? weak var animator : LTSliderAnimator? - internal var viewControllers = [String: UIViewController]() - internal var container : UIView? - internal var animated : Bool! + internal var viewControllers = [UITransitionContextViewControllerKey: UIViewController]() + internal var container : UIView + internal var _animated : Bool! internal var forward : Bool! var cancelled : Bool = false @@ -24,70 +25,70 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { internal var percentComplete : CGFloat! init(source: UIViewController?, destination: UIViewController?, containerView: UIView, animated: Bool, forward: Bool) { - super.init() - if nil != source { - viewControllers[UITransitionContextFromViewControllerKey] = source + viewControllers[UITransitionContextViewControllerKey.from] = source } if nil != destination { - viewControllers[UITransitionContextToViewControllerKey] = destination + viewControllers[UITransitionContextViewControllerKey.to] = destination } self.container = containerView - self.animated = animated + self._animated = animated self.forward = forward self.percentComplete = 1.0 + + super.init() } // MARK: - UIViewControllerContextTransitioning - func containerView() -> UIView? { + var containerView : UIView { return container } - func isAnimated() -> Bool { - return animated + var isAnimated : Bool { + return _animated } - func isInteractive() -> Bool { + var isInteractive : Bool { return nil != animator } - func transitionWasCancelled() -> Bool { + var transitionWasCancelled : Bool { return cancelled } - func presentationStyle() -> UIModalPresentationStyle { - return .Custom + var presentationStyle : UIModalPresentationStyle { + return .custom } - func targetTransform() -> CGAffineTransform { - return CGAffineTransformIdentity + var targetTransform : CGAffineTransform { + return CGAffineTransform.identity } - func viewControllerForKey(key: String) -> UIViewController? { + func viewController(forKey key: UITransitionContextViewControllerKey) -> UIViewController? { return viewControllers[key] } - func viewForKey(key: String) -> UIView? { + func view(forKey key: UITransitionContextViewKey) -> UIView? { switch key { - case UITransitionContextFromViewKey: - return viewControllerForKey(key)?.view + case UITransitionContextViewKey.from: + return viewController(forKey: UITransitionContextViewControllerKey.from)?.view - case UITransitionContextToViewKey: - return viewControllerForKey(key)?.view + case UITransitionContextViewKey.to: + return viewController(forKey: UITransitionContextViewControllerKey.to)?.view default: return nil } } - func initialFrameForViewController(vc: UIViewController) -> CGRect { - var result = CGRectZero - if let containerView = containerView() as UIView! { - if let key = allKeysForValue(viewControllers, value: vc).first as String! { + func initialFrame(for vc: UIViewController) -> CGRect { + var result = CGRect.zero + if let containerView = containerView as UIView! { + if let key = allKeysForValue(viewControllers, value: vc).first { switch key { - case UITransitionContextToViewControllerKey: + case UITransitionContextViewControllerKey.to: result = containerView.bounds if false == forward { @@ -96,7 +97,7 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { break - case UITransitionContextFromViewControllerKey: + case UITransitionContextViewControllerKey.from: result = containerView.bounds break @@ -109,12 +110,12 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { return result } - func finalFrameForViewController(vc: UIViewController) -> CGRect { - var result = CGRectZero - if let containerView = containerView() as UIView! { - if let key = allKeysForValue(viewControllers, value: vc).first as String! { + func finalFrame(for vc: UIViewController) -> CGRect { + var result = CGRect.zero + if let containerView = containerView as UIView! { + if let key = allKeysForValue(viewControllers, value: vc).first { switch key { - case UITransitionContextFromViewControllerKey: + case UITransitionContextViewControllerKey.from: result = containerView.bounds if true == forward { @@ -123,7 +124,7 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { break - case UITransitionContextToViewControllerKey: + case UITransitionContextViewControllerKey.to: result = containerView.bounds break @@ -133,29 +134,34 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { } } - let initialFrame = initialFrameForViewController(vc) - let offsetX = CGRectGetMinX(result) - CGRectGetMinX(initialFrame) - let offsetY = CGRectGetMinY(result) - CGRectGetMinY(initialFrame) - let offsetWidth = CGRectGetWidth(result) - CGRectGetWidth(initialFrame) - let offsetHeight = CGRectGetHeight(result) - CGRectGetHeight(initialFrame) + let initialFrame = self.initialFrame(for: vc) + let offsetX = result.minX - initialFrame.minX + let offsetY = result.minY - initialFrame.minY + let offsetWidth = result.width - initialFrame.width + let offsetHeight = result.height - initialFrame.height - let percents = isInteractive() ? percentComplete : 1.0 - result = CGRectOffset(initialFrame, offsetX * percents, offsetY * percents) - result.size.width += offsetWidth * percents - result.size.height += offsetHeight * percents + let percents = isInteractive ? percentComplete : 1.0 + result = initialFrame.offsetBy(dx: offsetX * percents!, dy: offsetY * percents!) + result.size.width += offsetWidth * percents! + result.size.height += offsetHeight * percents! return result } - func completeTransition(didComplete: Bool) { + func completeTransition(_ didComplete: Bool) { if let completionBlock = completionBlock as LTCompletionBlock! { - completionBlock(complete: didComplete) + completionBlock(didComplete) } } - func updateInteractiveTransition(complete: CGFloat) { + func updateInteractiveTransition(_ complete: CGFloat) { percentComplete = complete } + + @available(iOS 10.0, *) + func pauseInteractiveTransition() { + // FIXME? + } func finishInteractiveTransition() { cancelled = false @@ -165,7 +171,7 @@ class LTTransitionContext: NSObject, UIViewControllerContextTransitioning { cancelled = true } - func allKeysForValue(dictionary: [K : V], value: V) -> [K] { + func allKeysForValue(_ dictionary: [K : V], value: V) -> [K] { return dictionary.filter{ $0.1 == value }.map{ $0.0 } } diff --git a/LawTracker/Sources/UI/OTMLoadingView/OTMLoadingView.swift b/LawTracker/Sources/UI/OTMLoadingView/OTMLoadingView.swift index 67d2c72..6b0f75a 100644 --- a/LawTracker/Sources/UI/OTMLoadingView/OTMLoadingView.swift +++ b/LawTracker/Sources/UI/OTMLoadingView/OTMLoadingView.swift @@ -14,25 +14,25 @@ class OTMLoadingView: UIView { weak var rootView: UIView! - class func loadingView(rootView: UIView) -> OTMLoadingView { - let loadingView = NSBundle.mainBundle().loadNibNamed("OTMLoadingView", owner: self, options: nil).first as! OTMLoadingView + class func loadingView(_ rootView: UIView) -> OTMLoadingView { + let loadingView = Bundle.main.loadNibNamed("OTMLoadingView", owner: self, options: nil)?.first as! OTMLoadingView loadingView.show(rootView) return loadingView } - class func loadingView(rootView: UIView, message: String) -> OTMLoadingView { - let loadingView = NSBundle.mainBundle().loadNibNamed("OTMLoadingView", owner: self, options: nil).first as! OTMLoadingView + class func loadingView(_ rootView: UIView, message: String) -> OTMLoadingView { + let loadingView = Bundle.main.loadNibNamed("OTMLoadingView", owner: self, options: nil)?.first as! OTMLoadingView loadingView.showWithMessage(rootView, message: message) return loadingView } - private func show(rootView: UIView) { + fileprivate func show(_ rootView: UIView) { var frame = rootView.frame as CGRect - frame.origin = CGPointZero; + frame.origin = CGPoint.zero; self.frame = frame; rootView.addSubview(self) @@ -43,27 +43,27 @@ class OTMLoadingView: UIView { animate(1.0) } - private func animate(alpha: CGFloat) { - UIView.animateWithDuration(0.4, animations: { + fileprivate func animate(_ alpha: CGFloat) { + UIView.animate(withDuration: 0.4, animations: { self.alpha = alpha }, completion: {(finished: Bool) -> Void in }) } - private func showWithMessage(rootView: UIView, message: String) { + fileprivate func showWithMessage(_ rootView: UIView, message: String) { show(rootView) - loadingLabel.hidden = false + loadingLabel.isHidden = false loadingLabel.text = message } - func changeMessage(message: String) { + func changeMessage(_ message: String) { loadingLabel.text = message } func hide() { - if isDescendantOfView(rootView) { + if isDescendant(of: rootView) { animate(0.0) spinner.stopAnimating() removeFromSuperview() diff --git a/LawTracker/Sources/UI/OTMLoadingView/OTMView.swift b/LawTracker/Sources/UI/OTMLoadingView/OTMView.swift index bbe3545..171f4f1 100644 --- a/LawTracker/Sources/UI/OTMLoadingView/OTMView.swift +++ b/LawTracker/Sources/UI/OTMLoadingView/OTMView.swift @@ -16,12 +16,12 @@ class OTMView: UIView { showLoadingViewInView(self) } - func showLoadingViewWithMessage(message: String) { + func showLoadingViewWithMessage(_ message: String) { showLoadingViewInViewWithMessage(self, message: message) } - func showLoadingViewInView(view: UIView) { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + func showLoadingViewInView(_ view: UIView) { + DispatchQueue.main.async {[unowned self] in if !self.loadingViewShown { self.loadingView = OTMLoadingView.loadingView(view) self.loadingViewShown = true @@ -29,8 +29,8 @@ class OTMView: UIView { } } - func showLoadingViewInViewWithMessage(view: UIView, message: String) { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + func showLoadingViewInViewWithMessage(_ view: UIView, message: String) { + DispatchQueue.main.async {[unowned self] in if !self.loadingViewShown { self.loadingView = OTMLoadingView.loadingView(view, message: message) self.loadingViewShown = true @@ -41,7 +41,7 @@ class OTMView: UIView { } func hideLoadingView() { - dispatch_async(dispatch_get_main_queue()) {[unowned self] in + DispatchQueue.main.async {[unowned self] in if self.loadingViewShown { self.loadingView.hide() self.loadingView = nil diff --git a/LawTrackerTests/LawTrackerTests.swift b/LawTrackerTests/LawTrackerTests.swift index a501aa4..f7ebd7b 100644 --- a/LawTrackerTests/LawTrackerTests.swift +++ b/LawTrackerTests/LawTrackerTests.swift @@ -28,7 +28,7 @@ class LawTrackerTests: XCTestCase { func testPerformanceExample() { // This is an example of a performance test case. - self.measureBlock { + self.measure { // Put the code you want to measure the time of here. } } From bf837272af12f8c33312b650c093a81df96fd217 Mon Sep 17 00:00:00 2001 From: Emma Blink Date: Thu, 29 Jun 2017 18:37:06 +0300 Subject: [PATCH 2/3] =?UTF-8?q?Corrected=20=E2=80=9CAccept=E2=80=9D=20head?= =?UTF-8?q?er=20value=20for=20API=20requests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LawTracker/Sources/Client/LTClient.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/LawTracker/Sources/Client/LTClient.swift b/LawTracker/Sources/Client/LTClient.swift index 2e12d70..861b767 100644 --- a/LawTracker/Sources/Client/LTClient.swift +++ b/LawTracker/Sources/Client/LTClient.swift @@ -108,6 +108,7 @@ class LTClient: NSObject { if let url = result as URL! { if let request = NSMutableURLRequest(url: url) as NSMutableURLRequest! { request.httpMethod = "GET" + request.setValue("application/json", forHTTPHeaderField: "Accept") completionHandler(request as URLRequest, nil) } else { let requestError = LTClient.errorForMessage(LTClient.KLTMessages.nsRequestError + "\(url.absoluteString)") From 9d11528523acb0c6370c9f0043fe51bd0b94a7d0 Mon Sep 17 00:00:00 2001 From: Emma Blink Date: Fri, 30 Jun 2017 16:59:37 +0300 Subject: [PATCH 3/3] Updated view frames in storyboards to be consistent with their constraints --- LawTracker/Base.lproj/LaunchScreen.storyboard | 17 +- LawTracker/Base.lproj/Main.storyboard | 212 +++++++++--------- 2 files changed, 115 insertions(+), 114 deletions(-) diff --git a/LawTracker/Base.lproj/LaunchScreen.storyboard b/LawTracker/Base.lproj/LaunchScreen.storyboard index 4eb1895..639e16b 100644 --- a/LawTracker/Base.lproj/LaunchScreen.storyboard +++ b/LawTracker/Base.lproj/LaunchScreen.storyboard @@ -1,9 +1,13 @@ - - + + + + + - + + @@ -15,24 +19,23 @@ - + - + - + - diff --git a/LawTracker/Base.lproj/Main.storyboard b/LawTracker/Base.lproj/Main.storyboard index 92e4626..659c019 100644 --- a/LawTracker/Base.lproj/Main.storyboard +++ b/LawTracker/Base.lproj/Main.storyboard @@ -1,9 +1,13 @@ - - + + + + + - + + @@ -12,14 +16,13 @@ - - + @@ -30,20 +33,20 @@ - + - + - + - + - + @@ -65,7 +68,7 @@ - + @@ -85,11 +88,10 @@ - - + @@ -98,11 +100,10 @@ - - + @@ -113,45 +114,45 @@ - + - + - + - - + + - + - + - + - + - + @@ -185,13 +186,13 @@ - + @@ -204,7 +205,7 @@ - + @@ -213,7 +214,7 @@ - + @@ -228,7 +229,6 @@ - @@ -237,7 +237,7 @@ - + @@ -248,26 +248,26 @@ - + - + - + - + - + - + @@ -326,7 +326,7 @@ - + @@ -336,43 +336,43 @@ - + - + @@ -389,35 +389,35 @@ - - + + - + @@ -496,7 +496,7 @@ - + @@ -523,7 +523,6 @@ - @@ -547,27 +546,27 @@ - + - + - - + + - + - + @@ -598,10 +597,10 @@ - - - - + + + + Title @@ -613,30 +612,30 @@ - + - + @@ -649,7 +648,7 @@ - + @@ -677,7 +676,7 @@ - + @@ -693,11 +692,10 @@ - - + @@ -714,15 +712,15 @@ - + - + - + @@ -731,11 +729,11 @@ - + @@ -761,7 +759,7 @@ - + @@ -770,7 +768,7 @@ - + @@ -789,7 +787,7 @@ - +