//
//  YHURLEncodeHelper.swift
//  galaxy
//
//  Created by edy on 2024/9/20.
//  Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//

import UIKit

class YHURLEncodeHelper {
    
    // URL 编码
    class func urlEncodedString(_ str: String) -> String? {
        let allowedCharacterSet = CharacterSet(charactersIn: "!*'();:@&=+$,/?%#[]").inverted
        return str.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
    }

    // URL 解码
    class func urlDecodedString(_ str: String) -> String? {
        return str.removingPercentEncoding
    }

    // 检查是否为有效的 URL
    class func isUrlAddress(_ url: String) -> Bool {
        let regex = "((http[s]?|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www\\.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
        
        let urlPredicate = NSPredicate(format: "SELF MATCHES %@", regex)
        return urlPredicate.evaluate(with: url)
    }
}
