Created
February 6, 2015 19:43
-
-
Save davbeck/2eb46667dc774ffe50d1 to your computer and use it in GitHub Desktop.
TNKURLFormatter
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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