Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
TNKURLFormatter
//
// TNKURLFormatter.swift
//
// Created by David Beck on 2/6/15.
// Copyright (c) 2015 ThinkUltimate. All rights reserved.
//
import Foundation
class TNKURLFormatter: NSFormatter {
override func stringForObjectValue(obj: AnyObject) -> String? {
if let URL = obj as? NSURL {
return self.stringForURL(URL)
}
return nil
}
func stringForURL(URL: NSURL) -> String? {
return URL.absoluteString
}
override func getObjectValue(obj: AutoreleasingUnsafeMutablePointer<AnyObject?>, forString string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>) -> Bool {
if let URL = self.URLForString(string) {
obj.memory = URL
return true
} else {
error.memory = NSString.localizedStringWithFormat(NSLocalizedString("Could not convert \"%@\" to a valid URL.", comment: "Error message for converting strings to URLs."), string)
return false
}
}
func URLForString(userInput: String) -> NSURL? {
if let URL = NSURL(string: userInput) {
if URL.scheme != nil {
return URL
}
}
if let range = userInput.lowercaseString.rangeOfString("//") {
if range.startIndex == userInput.startIndex {
if let URL = NSURL(string: "http:" + userInput) {
return URL
}
}
}
return NSURL(string: "http://" + userInput)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment