mirror of
https://github.com/wahyd4/libr-ios.git
synced 2026-08-09 05:06:46 +10:00
58 lines
2.3 KiB
Swift
58 lines
2.3 KiB
Swift
//
|
|
// NSURL-Extensions.swift
|
|
// librx
|
|
//
|
|
// Created by Yunlong Zheng on 11/23/15.
|
|
// Copyright © 2015 librx. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
extension NSURL
|
|
{
|
|
|
|
class func validateUrl(urlString: String?, completion:(success: Bool, urlString: String? , error: NSString) -> Void)
|
|
{
|
|
// Description: This function will validate the format of a URL, re-format if necessary, then attempt to make a header request to verify the URL actually exists and responds.
|
|
// Return Value: This function has no return value but uses a closure to send the response to the caller.
|
|
|
|
var formattedUrlString : String?
|
|
|
|
// Ignore Nils & Empty Strings
|
|
if (urlString == nil || urlString == "")
|
|
{
|
|
completion(success: false, urlString: nil, error: "Url String was empty")
|
|
return
|
|
}
|
|
|
|
// Ignore prefixes (including partials)
|
|
let prefixes = ["http://www.", "https://www.", "www."]
|
|
for prefix in prefixes
|
|
{
|
|
if ((prefix.rangeOfString(urlString!, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil)) != nil){
|
|
completion(success: false, urlString: nil, error: "Url String was prefix only")
|
|
return
|
|
}
|
|
}
|
|
|
|
// Ignore URLs with spaces (NOTE - You should use the below method in the caller to remove spaces before attempting to validate a URL)
|
|
// Example:
|
|
// textField.text = textField.text.stringByReplacingOccurrencesOfString(" ", withString: "", options: nil, range: nil)
|
|
let range = urlString!.rangeOfCharacterFromSet(NSCharacterSet.whitespaceCharacterSet())
|
|
if let _ = range {
|
|
completion(success: false, urlString: nil, error: "Url String cannot contain whitespaces")
|
|
return
|
|
}
|
|
|
|
// Check that URL already contains required 'http://' or 'https://', prepend if it does not
|
|
formattedUrlString = urlString
|
|
if (!formattedUrlString!.hasPrefix("http://") && !formattedUrlString!.hasPrefix("https://"))
|
|
{
|
|
formattedUrlString = "http://"+urlString!
|
|
}
|
|
|
|
completion(success: true, urlString: urlString, error: "")
|
|
return
|
|
|
|
}
|
|
} |