2014-09-24 71 views
6

我有一個URL字符串追加到末尾變量,就像這樣:Swift URL字符串編碼在iOS上崩潰?

.../create?title=My Apartment 

我想逃避任何非有效的字符(如空格),但是當我嘗試這樣做,我崩潰在這兩個模擬器和我的設備上(的iOS 8.0)使用以下:

NSLog("Item1: \(item)") 
NSLog("Item2: \(item.title)") 

if let scrubbed = item.title.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) { 
    NSLog("Scrubbed: \(scrubbed)") 
} else { 
    NSLog("Nope!") 
} 

我看到在模擬器上,是這樣的:

2014-09-24 16:59:19.120 MyApp[16406:171349] Item1: MyApp.PostItem 
2014-09-24 16:59:19.121 MyApp[16406:171349] Item2: My Apartment 
2014-09-24 16:59:19.125 MyApp[16406:171349] Scrubbed: My    0X0P+0partment 

請注意該擦洗過的字符串的奇怪。一段時間後它崩潰抱怨一個構造不好的物體,這並不令人驚訝。

當我將設備上運行此,我在NSLog()聲明的EXC_BAD_ACCESS了試圖打印Scrubbed:

2014-09-24 17:04:37.378 MyApp[4346:2048259] Item1: MyApp.PostItem 
2014-09-24 17:04:37.379 MyApp[4346:2048259] Item2: My Apartment 

(lldb) po scrubbed 

error: <EXPR>:1:1: error: non-nominal type '$__lldb_context' cannot be extended 
extension $__lldb_context {        
^ 
<EXPR>:11:5: error: 'PostManager.Type' does not have a member named '$__lldb_wrapped_expr_3' 
    $__lldb_injected_self.$__lldb_wrapped_expr_3(  
    ^     ~~~~~~~~~~~~~~~~~~~~~~ 
(lldb) 

我怎樣才能弄清楚是怎麼回事崩潰?我希望看到Nope!在它像這樣崩潰之前打印在控制檯中。模型對象中的String值由UITextField提供。

編輯:我能得到從預淨化的值一些NSData輸出:

NSLog("Data: \(item.title.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false))") 
... 
2014-09-24 17:18:43.620 MyApp[4367:2051348] Data: Optional(<4d792041 70617274 6d656e74>) 

編輯2:我可以證實這一點崩潰在Xcode,並通行證在操場上。似乎是一個錯誤 - 但在哪裏? Xcode的?編譯器?運行?

編輯3:只有當我試圖用NSLog()打印變量值時,這個錯誤纔會出現。如果我完全避免這樣做,並且只需使用這個變量,大家都很開心。

回答

5

看起來像逃避NSCharacterSet.URLHostAllowedCharacterSet()生成奇怪的unicode字符串,強制在NSLog中崩潰,以防使用此字符串作爲第一個參數。

有一些方法來避免這種情況,你絕對應該使用它們:

  • 至於你使用這個網址查詢你一定要使用不同的characher集 - NSCharacterSet.URLQueryAllowedCharacterSet()

  • 使用print/println

  • 通行證scrubbedNSLog作爲參數NSLog("Scrubbed: %@", scrubbed)

這些 「變通」 的任何解決了這個問題。

+2

'NSLog(「%@」,url)'完全爲我工作。謝謝! – 2015-01-18 02:28:51