2015-08-18 20 views
50

Tôi đã sử dụng này, trong Swift 1,2Làm thế nào để sử dụng stringByAddingPercentEncodingWithAllowedCharacters() cho một URL trong Swift 2.0

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 

này bây giờ mang lại cho tôi một cảnh báo yêu cầu tôi sử dụng

stringByAddingPercentEncodingWithAllowedCharacters 

tôi cần phải sử dụng số NSCharacterSet làm đối số, nhưng có quá nhiều và tôi không thể xác định cái nào sẽ cho tôi kết quả giống như phương pháp đã sử dụng trước đây.

Một URL Ví dụ: Tôi muốn sử dụng sẽ như thế này

http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA 

URL Character Set để mã hóa dường như chứa bộ các cắt URL tôi. tức là,

Thành phần đường dẫn của URL là thành phần ngay sau thành phần máy chủ (nếu có). Nó kết thúc bất cứ nơi nào truy vấn hoặc đoạn bắt đầu. Ví dụ: trong URL http://www.example.com/index.php?key1=value1, thành phần đường dẫn là /index.php.

Tuy nhiên tôi không muốn cắt bất kỳ khía cạnh nào của nó. Khi tôi sử dụng Chuỗi của mình, ví dụ: myurlstring nó sẽ thất bại.

Nhưng khi được sử dụng như sau, thì không có vấn đề gì. Nó mã hóa chuỗi với một số phép thuật và tôi có thể lấy dữ liệu URL của mình.

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 

Vì nó

Trả về một đại diện của chuỗi bằng cách sử dụng mã hóa cho xác định phần trăm thoát cần thiết để chuyển đổi String thành một chuỗi URL pháp

Cảm ơn

Trả lời

126

Đối với chuỗi URL được tương đương với

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 

là bộ ký tự URLQueryAllowedCharacterSet

let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) 

Swift 3:

let urlwithPercentEscapes = myurlstring.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) 

Nó mã hóa tất cả mọi thứ sau khi câu hỏi đánh dấu trong UR L chuỗi.

Vì phương thức stringByAddingPercentEncodingWithAllowedCharacters có thể trả về 0, sử dụng các ràng buộc tùy chọn như được đề xuất trong câu trả lời của Leo Dabus.

+0

Làm cho tinh thần, cảm ơn - nếu bạn có thời gian, bạn có thể trợ giúp với http://stackoverflow.com/questions/32061298/could-geocodeaddressdictionary-in-ios-9-be- implementation-different-from-ios-8 – DogCoffee

+0

Tôi đã đăng câu trả lời – vadian

+0

nhờ câu trả lời hoàn hảo. một cho bạn. :) – Vats

16

Nó sẽ phụ thuộc vào url của bạn.Nếu url của bạn là một đường dẫn mà bạn có thể sử dụng các ký tự đặt urlPathAllowed

let myFileString = "My File.txt" 
if let urlwithPercentEscapes = myFileString.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) { 
    print(urlwithPercentEscapes) // "My%20File.txt" 
} 

Creating a Character Set for URL Encoding

urlFragmentAllowed

urlHostAllowed

urlPasswordAllowed

urlQueryA llowed

urlUserAllowed

Bạn có thể tạo cũng sở hữu bộ ký tự url của bạn:

let myUrlString = "http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA" 

let urlSet = CharacterSet.urlFragmentAllowed 
       .union(.urlHostAllowed) 
       .union(.urlPasswordAllowed) 
       .union(.urlQueryAllowed) 
       .union(.urlUserAllowed) 

extension CharacterSet { 
    static let urlAllowed = CharacterSet.urlFragmentAllowed 
             .union(.urlHostAllowed) 
             .union(.urlPasswordAllowed) 
             .union(.urlQueryAllowed) 
             .union(.urlUserAllowed) 
} 

if let urlwithPercentEscapes = myUrlString.addingPercentEncoding(withAllowedCharacters: .urlAllowed) { 
    print(urlwithPercentEscapes) // "http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red%20Lion&location=19036&location=1090%20N%20Charlotte%20St,%20Lancaster,%20PA" 
} 

lựa chọn khác là use URLComponents to properly create you url

+0

xem câu hỏi để biết thêm thông tin – DogCoffee

+0

bạn cần hiển thị loại url bạn đang sử dụng –

+3

Quan trọng hơn là bạn cần áp dụng bộ ký tự thích hợp cho từng phần của URL, không có giải pháp đơn lẻ nào. ... – Wain

2

Trong trường hợp của tôi, nơi các thành phần cuối cùng là ký tự không phải Latin Tôi đã làm như sau trong Swift 2.2:

extension String { 
func encodeUTF8() -> String? { 
//If I can create an NSURL out of the string nothing is wrong with it 
if let _ = NSURL(string: self) { 

    return self 
} 

//Get the last component from the string this will return subSequence 
let optionalLastComponent = self.characters.split { $0 == "/" }.last 


if let lastComponent = optionalLastComponent { 

    //Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String 
    let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +) 


    //Get the range of the last component 
    if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) { 
     //Get the string without its last component 
     let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex) 


     //Encode the last component 
     if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) { 


     //Finally append the original string (without its last component) to the encoded part (encoded last component) 
     let encodedString = stringWithoutLastComponent + lastComponentEncoded 

      //Return the string (original string/encoded string) 
      return encodedString 
     } 
    } 
} 

return nil; 
} 
} 
4

SWIFT 3,0

Từ grokswift

Tạo URL từ chuỗi là một mìn cho lỗi. Chỉ cần bỏ lỡ một/URL vô tình mã hóa? trong truy vấn và cuộc gọi API của bạn sẽ không thành công và ứng dụng của bạn sẽ không có bất kỳ dữ liệu nào để hiển thị (hoặc thậm chí là lỗi nếu bạn không lường trước được khả năng đó). Vì iOS 8 có cách tốt hơn để tạo URL bằng cách sử dụng NSURLComponentsNSURLQueryItems.

func createURLWithComponents() -> URL? { 
     var urlComponents = URLComponents() 
     urlComponents.scheme = "http" 
     urlComponents.host = "www.mapquestapi.com" 
     urlComponents.path = "/geocoding/v1/batch" 

     let key = URLQueryItem(name: "key", value: "YOUR_KEY_HERE") 
     let callback = URLQueryItem(name: "callback", value: "renderBatch") 
     let locationA = URLQueryItem(name: "location", value: "Pottsville,PA") 
     let locationB = URLQueryItem(name: "location", value: "Red Lion") 
     let locationC = URLQueryItem(name: "location", value: "19036") 
     let locationD = URLQueryItem(name: "location", value: "1090 N Charlotte St, Lancaster, PA") 

     urlComponents.queryItems = [key, callback, locationA, locationB, locationC, locationD] 

     return urlComponents.url 
} 

Dưới đây là mã để truy cập vào url sử dụng guard tuyên bố.

guard let url = createURLWithComponents() else { 
      print("invalid URL") 
      return nil 
     } 
     print(url) 

Output:

http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red%20Lion&location=19036&location=1090%20N%20Charlotte%20St,%20Lancaster,%20PA 
1

Trong Swift 3.1, tôi đang sử dụng một cái gì đó như sau:

let query = "param1=value1&param2=" + valueToEncode.addingPercentEncoding(withAllowedCharacters: .alphanumeric) 

Đó là an toàn hơn .urlQueryAllowed và những người khác, bởi vì nó sẽ mã hóa mọi ký tự khác với AZ, az và 0-9. Điều này hoạt động tốt hơn khi giá trị bạn đang mã hóa có thể sử dụng các ký tự đặc biệt như?, &, =, + và dấu cách.

Các vấn đề liên quan