How to make an NSURL that contains a | (pipe character)?

后端 未结 3 1524
天涯浪人
天涯浪人 2021-01-01 13:04

I am trying to access google maps\' forward geocoding service from my iphone app. When i try to make an NSURL from a string with a pipe in it I just get a nil pointer.

相关标签:
3条回答
  • 2021-01-01 13:24

    Have you tried replacing the pipe with %7C (the URL encoded value for the char |)?

    0 讨论(0)
  • 2021-01-01 13:31

    As stringByAddingPercentEscapesUsingEncoding is deprecated, you should use stringByAddingPercentEncodingWithAllowedCharacters.

    Swift answer:

    let rawUrlStr = "http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
    let urlEncoded = rawUrlStr.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
    let url = NSURL(string: urlEncoded)
    

    Edit: Swift 3 answer:

    let rawUrlStr = "http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
    if let urlEncoded = rawUrlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
        let url = NSURL(string: urlEncoded)
    }
    
    0 讨论(0)
  • 2021-01-01 13:37

    If you want to be safe for whatever weird characters you will put in the future, use stringByAddingPercentEscapesUsingEncoding method to make the string "URL-Friendly"...

    NSString *rawUrlStr = @"http://maps.google.com/maps/api/geocode/json?address=6th+and+pine&bounds=37.331689,-122.030731|37.331689,-122.030731&sensor=false";
    NSString *urlStr = [rawUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *searchURL = [NSURL URLWithString:urlStr];
    
    0 讨论(0)
提交回复
热议问题