diff --git a/.DS_Store b/.DS_Store index 7aee18b..ce76c55 100644 Binary files a/.DS_Store and b/.DS_Store differ diff --git a/AutocompleteTextfieldSwift.xcodeproj/project.pbxproj b/AutocompleteTextfieldSwift.xcodeproj/project.pbxproj index 53a9c2d..d64c5d4 100644 --- a/AutocompleteTextfieldSwift.xcodeproj/project.pbxproj +++ b/AutocompleteTextfieldSwift.xcodeproj/project.pbxproj @@ -207,14 +207,16 @@ attributes = { LastSwiftMigration = 0710; LastSwiftUpdateCheck = 0700; - LastUpgradeCheck = 0710; + LastUpgradeCheck = 0800; ORGANIZATIONNAME = mnbayan; TargetAttributes = { F96E31831A98DC35001DCEBF = { CreatedOnToolsVersion = 6.1; + LastSwiftMigration = 0800; }; F96E31981A98DC36001DCEBF = { CreatedOnToolsVersion = 6.1; + LastSwiftMigration = 0800; TestTargetID = F96E31831A98DC35001DCEBF; }; }; @@ -332,6 +334,7 @@ ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -344,7 +347,7 @@ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = YES; ONLY_ACTIVE_ARCH = YES; SDKROOT = iphoneos; @@ -375,13 +378,14 @@ ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - IPHONEOS_DEPLOYMENT_TARGET = 8.0; + IPHONEOS_DEPLOYMENT_TARGET = 10.0; MTL_ENABLE_DEBUG_INFO = NO; SDKROOT = iphoneos; TARGETED_DEVICE_FAMILY = "1,2"; @@ -400,6 +404,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = mnbayan.AutocompleteTextfieldSwift; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; @@ -415,6 +420,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = mnbayan.AutocompleteTextfieldSwift; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TARGETED_DEVICE_FAMILY = "1,2"; }; name = Release; @@ -435,6 +442,7 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "codefun.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AutocompleteTextfieldSwift.app/AutocompleteTextfieldSwift"; }; name = Debug; @@ -451,6 +459,8 @@ LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks @loader_path/Frameworks"; PRODUCT_BUNDLE_IDENTIFIER = "codefun.$(PRODUCT_NAME:rfc1034identifier)"; PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OPTIMIZATION_LEVEL = "-Owholemodule"; + SWIFT_VERSION = 3.0; TEST_HOST = "$(BUILT_PRODUCTS_DIR)/AutocompleteTextfieldSwift.app/AutocompleteTextfieldSwift"; }; name = Release; diff --git a/AutocompleteTextfieldSwift/AutoCompleteTextField/AutoCompleteTextField.swift b/AutocompleteTextfieldSwift/AutoCompleteTextField/AutoCompleteTextField.swift index a49cf03..8dab365 100644 --- a/AutocompleteTextfieldSwift/AutoCompleteTextField/AutoCompleteTextField.swift +++ b/AutocompleteTextfieldSwift/AutoCompleteTextField/AutoCompleteTextField.swift @@ -13,16 +13,16 @@ public class AutoCompleteTextField:UITextField { /// Manages the instance of tableview private var autoCompleteTableView:UITableView? /// Holds the collection of attributed strings - private lazy var attributedAutoCompleteStrings = [NSAttributedString]() + private lazy var attributedAutoCompleteStrings = [AttributedString]() /// Handles user selection action on autocomplete table view - public var onSelect:(String, NSIndexPath)->() = {_,_ in} + public var onSelect:(String, IndexPath)->() = {_,_ in} /// Handles textfield's textchanged public var onTextChange:(String)->() = {_ in} /// Font for the text suggestions - public var autoCompleteTextFont = UIFont.systemFontOfSize(12) + public var autoCompleteTextFont = UIFont.systemFont(ofSize: 12) /// Color of the text suggestions - public var autoCompleteTextColor = UIColor.blackColor() + public var autoCompleteTextColor = UIColor.black() /// Used to set the height of cell for each suggestions public var autoCompleteCellHeight:CGFloat = 44.0 /// The maximum visible suggestion @@ -39,7 +39,7 @@ public class AutoCompleteTextField:UITextField { public var hidesWhenEmpty:Bool?{ didSet{ assert(hidesWhenEmpty != nil, "hideWhenEmpty cannot be set to nil") - autoCompleteTableView?.hidden = hidesWhenEmpty! + autoCompleteTableView?.isHidden = hidesWhenEmpty! } } /// The table view height @@ -71,28 +71,28 @@ public class AutoCompleteTextField:UITextField { setupAutocompleteTable(superview!) } - public override func willMoveToSuperview(newSuperview: UIView?) { - super.willMoveToSuperview(newSuperview) + public override func willMove(toSuperview newSuperview: UIView?) { + super.willMove(toSuperview: newSuperview) commonInit() setupAutocompleteTable(newSuperview!) } private func commonInit(){ hidesWhenEmpty = true - autoCompleteAttributes = [NSForegroundColorAttributeName:UIColor.blackColor()] - autoCompleteAttributes![NSFontAttributeName] = UIFont.boldSystemFontOfSize(12) - self.clearButtonMode = .Always - self.addTarget(self, action: "textFieldDidChange", forControlEvents: .EditingChanged) - self.addTarget(self, action: "textFieldDidEndEditing", forControlEvents: .EditingDidEnd) + autoCompleteAttributes = [NSForegroundColorAttributeName:UIColor.black()] + autoCompleteAttributes![NSFontAttributeName] = UIFont.boldSystemFont(ofSize: 12) + self.clearButtonMode = .always + self.addTarget(self, action: #selector(AutoCompleteTextField.textFieldDidChange), for: .editingChanged) + self.addTarget(self, action: #selector(AutoCompleteTextField.textFieldDidEndEditing), for: .editingDidEnd) } - private func setupAutocompleteTable(view:UIView){ - let screenSize = UIScreen.mainScreen().bounds.size - let tableView = UITableView(frame: CGRectMake(self.frame.origin.x, self.frame.origin.y + CGRectGetHeight(self.frame), screenSize.width - (self.frame.origin.x * 2), 30.0)) + private func setupAutocompleteTable(_ view:UIView){ + let screenSize = UIScreen.main().bounds.size + let tableView = UITableView(frame: CGRect(x: self.frame.origin.x, y: self.frame.origin.y + self.frame.height, width: screenSize.width - (self.frame.origin.x * 2), height: 30.0)) tableView.dataSource = self tableView.delegate = self tableView.rowHeight = autoCompleteCellHeight - tableView.hidden = hidesWhenEmpty ?? true + tableView.isHidden = hidesWhenEmpty ?? true view.addSubview(tableView) autoCompleteTableView = tableView @@ -113,13 +113,13 @@ public class AutoCompleteTextField:UITextField { let attrs = [NSForegroundColorAttributeName:autoCompleteTextColor, NSFontAttributeName:autoCompleteTextFont] if attributedAutoCompleteStrings.count > 0 { - attributedAutoCompleteStrings.removeAll(keepCapacity: false) + attributedAutoCompleteStrings.removeAll(keepingCapacity: false) } if let autoCompleteStrings = autoCompleteStrings, let autoCompleteAttributes = autoCompleteAttributes { for i in 0.. Void in - self.autoCompleteTableView?.hidden = self.hidesWhenEmpty! ? self.text!.isEmpty : false + DispatchQueue.main.async(execute: { () -> Void in + self.autoCompleteTableView?.isHidden = self.hidesWhenEmpty! ? self.text!.isEmpty : false }) } func textFieldDidEndEditing() { - autoCompleteTableView?.hidden = true + autoCompleteTableView?.isHidden = true } } //MARK: - UITableViewDataSource - UITableViewDelegate extension AutoCompleteTextField: UITableViewDataSource, UITableViewDelegate { - public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { + public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return autoCompleteStrings != nil ? (autoCompleteStrings!.count > maximumAutoCompleteCount ? maximumAutoCompleteCount : autoCompleteStrings!.count) : 0 } - public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { + public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cellIdentifier = "autocompleteCellIdentifier" - var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) + var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) if cell == nil{ - cell = UITableViewCell(style: .Default, reuseIdentifier: cellIdentifier) + cell = UITableViewCell(style: .default, reuseIdentifier: cellIdentifier) } if enableAttributedText{ - cell?.textLabel?.attributedText = attributedAutoCompleteStrings[indexPath.row] + cell?.textLabel?.attributedText = attributedAutoCompleteStrings[(indexPath as NSIndexPath).row] } else{ cell?.textLabel?.font = autoCompleteTextFont cell?.textLabel?.textColor = autoCompleteTextColor - cell?.textLabel?.text = autoCompleteStrings![indexPath.row] + cell?.textLabel?.text = autoCompleteStrings![(indexPath as NSIndexPath).row] } cell?.contentView.gestureRecognizers = nil return cell! } - public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { - let cell = tableView.cellForRowAtIndexPath(indexPath) + public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { + let cell = tableView.cellForRow(at: indexPath) if let selectedText = cell?.textLabel?.text { self.text = selectedText onSelect(selectedText, indexPath) } - dispatch_async(dispatch_get_main_queue(), { () -> Void in - tableView.hidden = self.hidesWhenSelected + DispatchQueue.main.async(execute: { () -> Void in + tableView.isHidden = self.hidesWhenSelected }) } - public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) { - if cell.respondsToSelector("setSeparatorInset:"){ + public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { + if cell.responds(to: #selector(setter: UITableViewCell.separatorInset)){ cell.separatorInset = autoCompleteSeparatorInset } - if cell.respondsToSelector("setPreservesSuperviewLayoutMargins:"){ + if cell.responds(to: #selector(setter: UIView.preservesSuperviewLayoutMargins)){ cell.preservesSuperviewLayoutMargins = false } - if cell.respondsToSelector("setLayoutMargins:"){ + if cell.responds(to: #selector(setter: UIView.layoutMargins)){ cell.layoutMargins = autoCompleteSeparatorInset } } - public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { + public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return autoCompleteCellHeight } } diff --git a/AutocompleteTextfieldSwift/Controllers/AppDelegate.swift b/AutocompleteTextfieldSwift/Controllers/AppDelegate.swift index 8d147e4..12048e6 100644 --- a/AutocompleteTextfieldSwift/Controllers/AppDelegate.swift +++ b/AutocompleteTextfieldSwift/Controllers/AppDelegate.swift @@ -14,30 +14,30 @@ class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? - func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } - func applicationWillResignActive(application: UIApplication) { + func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - func applicationDidEnterBackground(application: UIApplication) { + func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - func applicationWillEnterForeground(application: UIApplication) { + func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - func applicationDidBecomeActive(application: UIApplication) { + func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - func applicationWillTerminate(application: UIApplication) { + func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } diff --git a/AutocompleteTextfieldSwift/Controllers/ViewController.swift b/AutocompleteTextfieldSwift/Controllers/ViewController.swift index 3217175..c6a5188 100644 --- a/AutocompleteTextfieldSwift/Controllers/ViewController.swift +++ b/AutocompleteTextfieldSwift/Controllers/ViewController.swift @@ -16,7 +16,7 @@ class ViewController: UIViewController { private var responseData:NSMutableData? private var selectedPointAnnotation:MKPointAnnotation? - private var dataTask:NSURLSessionDataTask? + private var dataTask:URLSessionDataTask? private let googleMapsKey = "AIzaSyDg2tlPcoqxx2Q2rfjhsAKS-9j0n3JA_a4" private let baseURLString = "https://maps.googleapis.com/maps/api/place/autocomplete/json" @@ -42,7 +42,7 @@ class ViewController: UIViewController { autocompleteTextfield.hidesWhenEmpty = true autocompleteTextfield.enableAttributedText = true var attributes = [String:AnyObject]() - attributes[NSForegroundColorAttributeName] = UIColor.blackColor() + attributes[NSForegroundColorAttributeName] = UIColor.black() attributes[NSFontAttributeName] = UIFont(name: "HelveticaNeue-Bold", size: 12.0) autocompleteTextfield.autoCompleteAttributes = attributes } @@ -68,7 +68,7 @@ class ViewController: UIViewController { } //MARK: - Private Methods - private func addAnnotation(coordinate:CLLocationCoordinate2D, address:String?){ + private func addAnnotation(_ coordinate:CLLocationCoordinate2D, address:String?){ if let annotation = selectedPointAnnotation{ mapView.removeAnnotation(annotation) } @@ -79,18 +79,19 @@ class ViewController: UIViewController { mapView.addAnnotation(selectedPointAnnotation!) } - private func fetchAutocompletePlaces(keyword:String) { + private func fetchAutocompletePlaces(_ keyword:String) { let urlString = "\(baseURLString)?key=\(googleMapsKey)&input=\(keyword)" - let s = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet - s.addCharactersInString("+&") - if let encodedString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(s) { - if let url = NSURL(string: encodedString) { - let request = NSURLRequest(URL: url) - dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in + var allowedURLCharacters = CharacterSet.urlQueryAllowed + allowedURLCharacters.insert(charactersIn: "+&") + + if let encodedString = urlString.addingPercentEncoding(withAllowedCharacters: allowedURLCharacters) { + if let url = URL(string: encodedString) { + let request = URLRequest(url: url) + dataTask = URLSession.shared.dataTask(with: request, completionHandler: { (data, response, error) -> Void in if let data = data{ do{ - let result = try NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) + let result = try JSONSerialization.jsonObject(with: data, options: .allowFragments) if let status = result["status"] as? String{ if status == "OK"{ @@ -99,14 +100,14 @@ class ViewController: UIViewController { for dict in predictions as! [NSDictionary]{ locations.append(dict["description"] as! String) } - dispatch_async(dispatch_get_main_queue(), { () -> Void in + DispatchQueue.main.async(execute: { () -> Void in self.autocompleteTextfield.autoCompleteStrings = locations }) return } } } - dispatch_async(dispatch_get_main_queue(), { () -> Void in + DispatchQueue.main.async(execute: { () -> Void in self.autocompleteTextfield.autoCompleteStrings = nil }) } diff --git a/AutocompleteTextfieldSwift/Helpers/Location.swift b/AutocompleteTextfieldSwift/Helpers/Location.swift index 7fcfbaf..063e6cd 100644 --- a/AutocompleteTextfieldSwift/Helpers/Location.swift +++ b/AutocompleteTextfieldSwift/Helpers/Location.swift @@ -11,7 +11,7 @@ import CoreLocation class Location{ - class func geocodeAddressString(address:String, completion:(placemark:CLPlacemark?, error:NSError?)->Void){ + class func geocodeAddressString(_ address:String, completion:(placemark:CLPlacemark?, error:NSError?)->Void){ let geocoder = CLGeocoder() geocoder.geocodeAddressString(address, completionHandler: { (placemarks, error) -> Void in if error == nil{ @@ -25,7 +25,7 @@ class Location{ }) } - class func reverseGeocodeLocation(location:CLLocation,completion:(placemark:CLPlacemark?, error:NSError?)->Void){ + class func reverseGeocodeLocation(_ location:CLLocation,completion:(placemark:CLPlacemark?, error:NSError?)->Void){ let geoCoder = CLGeocoder() geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in if let err = error{ @@ -38,7 +38,7 @@ class Location{ }) } - class func addressFromPlacemark(placemark:CLPlacemark)->String{ + class func addressFromPlacemark(_ placemark:CLPlacemark)->String{ var address = "" if let name = placemark.addressDictionary?["Name"] as? String { @@ -60,14 +60,14 @@ class Location{ return address } - private class func constructAddressString(string:String, newString:String)->String{ + private class func constructAddressString(_ string:String, newString:String)->String{ var address = string if !address.isEmpty{ - address = address.stringByAppendingString(", \(newString)") + address = address + ", \(newString)" } else{ - address = address.stringByAppendingString(newString) + address = address + newString } return address } -} \ No newline at end of file +} diff --git a/AutocompleteTextfieldSwift/Helpers/MKMapViewExtension.swift b/AutocompleteTextfieldSwift/Helpers/MKMapViewExtension.swift index 508528a..8e3d1ba 100644 --- a/AutocompleteTextfieldSwift/Helpers/MKMapViewExtension.swift +++ b/AutocompleteTextfieldSwift/Helpers/MKMapViewExtension.swift @@ -16,24 +16,24 @@ let DEGREES = 180.0 extension MKMapView{ //MARK: Map Conversion Methods - private func longitudeToPixelSpaceX(longitude:Double)->Double{ + private func longitudeToPixelSpaceX(_ longitude:Double)->Double{ return round(MERCATOR_OFFSET + MERCATOR_RADIUS * longitude * M_PI / DEGREES) } - private func latitudeToPixelSpaceY(latitude:Double)->Double{ + private func latitudeToPixelSpaceY(_ latitude:Double)->Double{ return round(MERCATOR_OFFSET - MERCATOR_RADIUS * log((1 + sin(latitude * M_PI / DEGREES)) / (1 - sin(latitude * M_PI / DEGREES))) / 2.0) } - private func pixelSpaceXToLongitude(pixelX:Double)->Double{ + private func pixelSpaceXToLongitude(_ pixelX:Double)->Double{ return ((round(pixelX) - MERCATOR_OFFSET) / MERCATOR_RADIUS) * DEGREES / M_PI } - private func pixelSpaceYToLatitude(pixelY:Double)->Double{ + private func pixelSpaceYToLatitude(_ pixelY:Double)->Double{ return (M_PI / 2.0 - 2.0 * atan(exp((round(pixelY) - MERCATOR_OFFSET) / MERCATOR_RADIUS))) * DEGREES / M_PI } - private func coordinateSpanWithCenterCoordinate(centerCoordinate:CLLocationCoordinate2D, zoomLevel:Double)->MKCoordinateSpan{ + private func coordinateSpanWithCenterCoordinate(_ centerCoordinate:CLLocationCoordinate2D, zoomLevel:Double)->MKCoordinateSpan{ // convert center coordiate to pixel space let centerPixelX = longitudeToPixelSpaceX(centerCoordinate.longitude) @@ -64,7 +64,8 @@ extension MKMapView{ return MKCoordinateSpan(latitudeDelta: latitudeDelta, longitudeDelta: longitudeDelta) } - func setCenterCoordinate(centerCoordinate:CLLocationCoordinate2D, var zoomLevel:Double, animated:Bool){ + func setCenterCoordinate(_ centerCoordinate:CLLocationCoordinate2D, zoomLevel:Double, animated:Bool){ + var zoomLevel = zoomLevel // clamp large numbers to 28 zoomLevel = min(zoomLevel, 28) @@ -79,4 +80,4 @@ extension MKMapView{ } } -} \ No newline at end of file +} diff --git a/AutocompleteTextfieldSwiftTests/AutocompleteTextfieldSwiftTests.swift b/AutocompleteTextfieldSwiftTests/AutocompleteTextfieldSwiftTests.swift index cfc44fc..b73ee58 100644 --- a/AutocompleteTextfieldSwiftTests/AutocompleteTextfieldSwiftTests.swift +++ b/AutocompleteTextfieldSwiftTests/AutocompleteTextfieldSwiftTests.swift @@ -28,7 +28,7 @@ class AutocompleteTextfieldSwiftTests: 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. } }