1// Copyright 2012 The Chromium Authors 2// Use of this source code is governed by a BSD-style license that can be 3// found in the LICENSE file. 4 5#import "net/base/apple/url_conversions.h" 6 7#import <Foundation/Foundation.h> 8 9#include "base/strings/escape.h" 10#include "url/gurl.h" 11#include "url/url_canon.h" 12 13namespace net { 14 15NSURL* NSURLWithGURL(const GURL& url) { 16 if (!url.is_valid()) { 17 return nil; 18 } 19 20 // NSURL strictly enforces RFC 1738 which requires that certain characters 21 // are always encoded. These characters are: "<", ">", """, "#", "%", "{", 22 // "}", "|", "\", "^", "~", "[", "]", and "`". 23 // 24 // GURL leaves some of these characters unencoded in the path, query, and 25 // ref. This function manually encodes those components, and then passes the 26 // result to NSURL. 27 GURL::Replacements replacements; 28 std::string escaped_path = base::EscapeNSURLPrecursor(url.path()); 29 std::string escaped_query = base::EscapeNSURLPrecursor(url.query()); 30 std::string escaped_ref = base::EscapeNSURLPrecursor(url.ref()); 31 if (!escaped_path.empty()) { 32 replacements.SetPathStr(escaped_path); 33 } 34 if (!escaped_query.empty()) { 35 replacements.SetQueryStr(escaped_query); 36 } 37 if (!escaped_ref.empty()) { 38 replacements.SetRefStr(escaped_ref); 39 } 40 GURL escaped_url = url.ReplaceComponents(replacements); 41 42 NSString* escaped_url_string = 43 [NSString stringWithUTF8String:escaped_url.spec().c_str()]; 44 return [NSURL URLWithString:escaped_url_string]; 45} 46 47GURL GURLWithNSURL(NSURL* url) { 48 if (url) { 49 return GURL(url.absoluteString.UTF8String); 50 } 51 return GURL(); 52} 53 54} // namespace net 55