转载自:https://www.reddit.com/r/swift/comments/2w19kp/how_do_you_send_a_through_nsmutableurlrequest/

 

how do you send a ? through NSMutableURLRequest without encoding the ? as %3F (self.swift)

submitted 1 year ago by xStory_Timex

I have a enum Router.swift that helps me use alamofire to interact with my API.

recently i changed the API and now when i send a URL request my code changes the "?" to "%3F" which i believe is "?" in url encoding.

here is the code Look at .ReadBrandProducts /products?brand_id=(id) when the id is 1 the request comes back as /products%3Fbrand_id=1

var path: String {
    switch self {
    case .AddReview(let id, _):
        return "/products/\(id)/reviews"
    case .ReadBrands:
        return "/brands"
    case .ReadBrandProducts(let id):
        return "/products?brand_id=\(id)"
    case .ReadProductData(let id):
        return "/products/\(id)"
    case .ReadReviews(let id):
        return "/products/\(id)/reviews"
    case .Favorite(let id):
        return "/products/\(id)/favorite"
    case .readFeed:
        return "/activity"
    }
}

// MARK: URLRequestConvertible

var URLRequest: NSURLRequest {
    let URL = NSURL(string: Router.baseURLString)!
    let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
    mutableURLRequest.HTTPMethod = method.rawValue

    if let token = KeychainService.loadToken() {
        mutableURLRequest.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    }
 
 
 
 

 

[–]lyinstevemod 2 points 1 year ago 

If you're using Alamofire, you should really be submitting URL encoded parameters as a dictionary instead, because Alamofire handles serialization. You're doing more work than you should.

 

[–]xStory_Timex[S1 point 1 year ago 

I don't understand, can you explain more

 

[–]lyinstevemod 1 point 1 year ago 

So right now you're adding URL parameters, right? And you're serializing them into a string yourself.

You also said you're using Alamofire. Alamofire will actually take those arguments in a Dictionary as a parameter to the request() function. You don't need to -- and shouldn't -- manually create those strings.

Specifically just

?brand_id=\(id)

Instead, pass the parameters into the Alamofire request() function.

Alamofire.request(
   .GET,
   "/products",
   parameters: ["brand_id": id]
)
 
 
 
 
 
 
 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
  • 2021-07-04
  • 2021-07-28
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-14
  • 2021-06-13
  • 2022-12-23
  • 2021-07-17
  • 2021-06-20
相关资源
相似解决方案