2017-09-26 65 views
2

大家下午好,新手在這裏試圖學習Swift/Alamofire。我已經掙扎了近兩天,並準備繼續前進。Alamofire編碼invalidURL

我的URL看起來已經被創建了,但是在提出請求時出現錯誤。在查看Xcode調試日誌時,看起來好像我的單引號在請求發送時正在被轉義。

let owner : String = "[email protected]" 

func getDeploymentsByOwner(token: String, owner: String, success: @escaping (JSON) -> Void, failure: @escaping (Error) -> Void) { 

    let headers = [ 
     "Authorization": "Bearer \(token)", 
     ] 
    print(owner) 


    let url = "https://corp.local?$filter=owners/ref eq '\(owner)'" 


    // created URL is https://corp.local?$filter=owners/ref eq '[email protected]' 


    Alamofire.request(url, method: .get, encoding: URLEncoding.queryString, headers: headers).responseJSON { (responseObject) -> Void in 
     if responseObject.result.isSuccess { 
      let resJSON = JSON(responseObject.result.value!) 
      success(resJSON) 
     } 
     if responseObject.result.isFailure { 
      let error = responseObject.result.error 
      print(error) 
      failure(error!) 
     } 
    } 

我的錯誤消息看起來像這樣 // Xocde調試錯誤

Optional(Alamofire.AFError.invalidURL("https//:corp.local?$filter=owners/ref eq \'[email protected]\'")) 
invalidURL(https://corp.local?$filter=owners/ref eq \'[email protected]\'") 

我能不$過濾器中的所有項目,所以只要省略了過濾器的要求工作。

//郵差的工作原理與生成的URL,但一用反斜槓()將不會

+0

嘗試對網址進行編碼 –

+0

感謝您的反饋。你如何編碼它? – TryingToMakeItWork

+0

你能解決這個問題嗎? –

回答

1

請檢查:

let url = "https//:corp.local?$filter=owners/ref eq \'[email protected]\'" 
let urlEncoded = url.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) 
print(urlEncoded!) 
1

謝謝您的答覆,可惜沒有奏效。整個網址包含主機名稱。但它確實給了我一個解決問題的出發點,謝謝。工作代碼低於

let url = "https://corp.local?$filter=owners/ref eq '\(owner)'" 
    let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)