I have a simple GET request for login. Username is Silver and password is MOto

I am using SwiftHttp framework for handling requests. On hitting login request, I always get response as false.
However on hitting the login request url on browser (replaced actual domain with server) I get true :
https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26#10
There is something wrong with encoding & in the password. Though I have replaced it with percent encoding. Here is my code :
do {
let passwordString = self.convertSpecialCharacters(string: password.text!)
print("%#", passwordString)
let opt = try HTTP.GET(Constants.kLoginUrl, parameters: ["login": username.text!, "pass": passwordString])
opt.start { response in
if let err = response.error {
print("error: \(err.localizedDescription)")
return
}
print("opt finished: \(response.description)")
self.parseLoginResponse(response.data)
}
} catch _ as NSError {
}
And this is convertSpecialCharacters :
func convertSpecialCharacters(string: String) -> String {
var newString = string
let arrayEncode = ["&", "<", ">", "\"", "'", "-", "..."]
for (escaped_char) in arrayEncode {
newString = newString.encode(escaped_char)
}
return newString
}
Extension for encoding :
extension String {
func encode(_ chars: String) -> String
{
let forbidden = CharacterSet(charactersIn: chars)
return self.addingPercentEncoding(withAllowedCharacters: forbidden.inverted) ?? self
}
}
A suitable way is to use URLComponents which handles all percent encoding:
var urlComponents = URLComponents(string: "https://server/api/check-access/by-login-pass")!
let queryItems = [URLQueryItem(name:"_key", value:"wlyOF7TM8Y3tn19KUdlq"),
URLQueryItem(name:"login", value:"silver"),
URLQueryItem(name:"pass", value:"MOto
")]
urlComponents.queryItems = queryItems
let url = urlComponents.url
print(url) // "https://server/api/check-access/by-login-pass?_key=wlyOF7TM8Y3tn19KUdlq&login=silver&pass=MOto%26#10"
PS: I totally agree with luk2302's comment.
I've decided to go full custom for my GET-request, since everything else didn't want to work and got me angry. I used the request for something different though, like getting a list from our server. The login is done via POST requests which was easier.
However, to stick with GET-requests:
I needed characters like "+" and "/" encoded...
First I couldn't get the "+" encoded with the "stringByAddingPercentEncodingWithAllowedCharacters" method.
So I have built my own extension for String:
extension String
{
return CFURLCreateStringByAddingPercentEscapes(
nil,
self as CFString,
nil,
"!*'();:#&=+$,/?%#[]" as CFString,
CFStringBuiltInEncodings.UTF8.rawValue
) as String
}
2nd step was to add this to my url for the final request. I wanted to use URLQueryItems and add them to the url by using url.query or url.queryItems. Bad surprise: My already correctly encoded string got encoded again and every "%" inside of it became "%25" making it invalid. -.-
So now I have appended each encoded value to a string which will be added to the url. Doesn't feel very "swift" but ok..
let someUrl = "https://example.com/bla/bla.json"
var queryString = ""
var index = 0
// dicParam is of type [String: AnyObject] with all needed keys and values for the query
for (key, value) in dicParam
{
let encodedValue = (value as! String).encodeUrl()
if index != 0
{
queryString.append("&\(key)=\(encodedValue)")
}
else
{
queryString.append("?\(key)=\(encodedValue)")
}
index += 1
}
let url = URLComponents(string: someUrl + queryString)!
Hope this helps someone and saves a few hours :/
Related
I have a function that takes an image and a string. When I try to put the string into a longer string using the () ability, it tells me it finds nil while unwrapping an optional. Exception it's not an optional at all, it's a string. I can print the value out and it comes out correctly.
func UpdateBusiness(logo: UIImage, category: String) {
guard let bizID = UserDefaults.standard.string(forKey: defaultKeys.businessID) else {return}
let thisURL = "http://mywebsite.com/api/v0.1/Business/EditBusinessLogoAndCategory?businessID=\(bizID)&category=\(category)"
let combinedURL = URL(string: thisURL)!
}
creating the URL crashes the system. I can see the value of category in the debugger, and I have no optionals in this string. How can it find nil?
This code is crashing due to force unwrapping. In this case can recommend to use URLComponents.This is more readable than the string joining and for large number of parameter string joining is not a good option.
var components = URLComponents()
components.scheme = "http"
components.host = "mywebsite.com"
components.path = "/api/v0.1/Business/EditBusinessLogoAndCategory"
components.queryItems = [
URLQueryItem(name: "businessID", value: bizID),
URLQueryItem(name: "category", value: category)
]
let url = components.url
enter code here
I have the string below and I would like to remove this part "https://drive.google.com/open?id=" so that my string only has "1FN7S3N_9IAkWYMjLnqh4BKsh8_YT0Zma" Any suggestions? Thanks!
let string = "https://drive.google.com/open?id=1FN7S3N_9IAkWYMjLnqh4BKsh8_YT0Zma"
URL could have other parameters so just replacing string might not be a good solution. URLComponents comes in handy for this.
func getQueryStringParameter(url: String, param: String) -> String? {
return URLComponents(string: url)?.queryItems?.first{ $0.name == param }?.value
}
And use it like this.
let string = "https://drive.google.com/open?id=1FN7S3N_9IAkWYMjLnqh4BKsh8_YT0Zma"
if let id = getQueryStringParameter(url: string, param: "id") {
print(id)
}
Get 2nd component separated by google drive part:
let string = "https://drive.google.com/open?id=1FN7S3N_9IAkWYMjLnqh4BKsh8_YT0Zma"
let id = string.components(separatedBy: "https://drive.google.com/open?id=")[1]
Replace google drive part with empty string:
let string = "https://drive.google.com/open?id=1FN7S3N_9IAkWYMjLnqh4BKsh8_YT0Zma"
let id = string.replacingOccurrences(of: "https://drive.google.com/open?id=", with: "")
I got json data from server like this.
[
"http:\/\/helloWord.com\/user\/data\/000001.jpg?1497514193433",
"http:\/\/helloWord.com\/user\/data\/000002.jpg?1500626693722"
]
And What should I do to get each user url?
I try to use removingPercentEncoding, but it doesn't work.
What should I do?
Thanks.
let string:String = chatroom.avatar
let tempArr = string.components(separatedBy: ",")
var stringArr = Array<String>()
print("**tempArr\(tempArr)")
for a in tempArr {
var b = a.replacingOccurrences(of: "\"", with: "")
b = b.replacingOccurrences(of: "[", with: "")
b = b.replacingOccurrences(of: "]", with: "")
b = b.removingPercentEncoding //not working!!!!
print("b: \(b)")
//b: http:\/\/helloWord.com\/user\/data\/000001.jpg?1497514193433
//b: http:\/\/helloWord.com\/user\/data\/000002.jpg?1500626693722
}
I use swiftyJson
class User : Model {
var url:String = ""
func fromJson(_ json:JSON) {
url = json["url"].zipString
saveSqlite()
}
}
extension JSON {
var prettyString: String {
if let string = rawString() {
return string
}
return ""
}
var zipString: String {
if let string = rawString(.utf8, options: JSONSerialization.WritingOptions.init(rawValue: 0)) {
return string
}
return ""
}
}
Err, you shouldn't try to write your own JSON parser.
Try: https://github.com/SwiftyJSON/SwiftyJSON
It is one file of Swift code and makes using JSON much easier in Swift.
In swift 4 you will be able to use Structs to directly decode, but we're not there yet.
The apple way:
func read(payload: Data) throws -> [String]? {
guard let result = try JSONSerialization.jsonObject(with: payload, options: JSONSerialization.ReadingOptions.allowFragments) as? [String] else { return nil }
return result
}
Then for example you could read them out this way:
var userURLs: [URL] = []
for jsonURL in result {
guard let userURL = URL(string: jsonURL) else { continue }
userURLs.append(userURL)
}
This way you get only valid URL objects in your last result array.
If you get problems using the JSONSerialization code I described above it might be that it expects a different type. Then you'd have to use [Any] as a cast instead, or in case you have objects [String: Any] usually works. Keep in mind that in that case you will have to cast the objects you get from the array like so:
URL(string: (jsonURL as? String) ?? "")
Swifty JSON makes it easier to go about with the nullability, as it provides an easy way to safely traverse an object tree and return empty but non nil values!
It seems to me that you want to use removingPercentEncoding to remove escape characters - those backslashes? While removingPercentEncoding is to work on percent encoded characters, e.g. to convert http%3A%2F%2Fwww.url-encode-decode.com%2F to http://www.url-encode-decode.com/. So you are using it at the wrong place. Make sure to call this method only on the URLs that are percent encoded.
For this scenario, like others already suggested, use JSONSerialization is the way to go.
How could we convert anyobject to string in swift 3, it's very easy in the older version by using.
var str = toString(AnyObject)
I tried String(AnyObject) but the output is always optional, even when i'm sure that AnyObject is not a optional value.
The compiler suggests that you replace your code with:
let s = String(describing: str)
One other option is available if you have a situation where you want to silently fail with an empty string rather than store something that might not originally be a string as a string.
let s = str as? String ?? ""
else you have the ways of identifying and throwing an error in the answers above/below.
Here's three options for you:
Option 1 - if let
if let b = a as? String {
print(b) // Was a string
} else {
print("Error") // Was not a string
}
Option 2 - guard let
guard let b = a as? String
else {
print("Error") // Was not a string
return // needs a return or break here
}
print(b) // Was a string
Option 3 - let with ?? (null coalescing operator)
let b = a as? String ?? ""
print(b) // Print a blank string if a was not a string
Here's a simple function (repl.it) that will mash any value into a string, with nil becoming an empty string. I found it useful for dealing with JSON that inconsistently uses null, blank, numbers, and numeric strings for IDs.
import Foundation
func toString(_ value: Any?) -> String {
return String(describing: value ?? "")
}
let d: NSDictionary = [
"i" : 42,
"s" : "Hello, World!"
]
dump(toString(d["i"]))
dump(toString(d["s"]))
dump(toString(d["x"]))
Prints:
- "42"
- "Hello, World!"
- ""
Try
let a = "Test" as AnyObject
guard let b = a as? String else { // Something went wrong handle it here }
print(b) // Test
try this -
var str:AnyObject?
str = "Hello, playground" as AnyObject?
if let value = str
{
var a = value as! String
}
OR
var a = str as? String
I am using Swift 1.2 to develop my iPhone application and I am communicating with a http web service.
The response I am getting is in query string format (key-value pairs) and URL encoded in .Net.
I can get the response, but looking the proper way to decode using Swift.
Sample response is as follows
status=1&message=The+transaction+for+GBP+12.50+was+successful
Tried following way to decode and get the server response
// This provides encoded response String
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
var decodedResponse = responseString.stringByReplacingEscapesUsingEncoding(NSUTF8StringEncoding)!
How can I replace all URL escaped characters in the string?
To encode and decode urls create this extention somewhere in the project:
Swift 2.0
extension String
{
func encodeUrl() -> String
{
return self.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
}
func decodeUrl() -> String
{
return self.stringByRemovingPercentEncoding
}
}
Swift 3.0
extension String
{
func encodeUrl() -> String
{
return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed())
}
func decodeUrl() -> String
{
return self.removingPercentEncoding
}
}
Swift 4.1
extension String
{
func encodeUrl() -> String?
{
return self.addingPercentEncoding( withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
}
func decodeUrl() -> String?
{
return self.removingPercentEncoding
}
}
Swift 2 and later (Xcode 7)
var s = "aa bb -[:/?&=;+!##$()',*]";
let sEncode = s.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
let sDecode = sEncode?.stringByRemovingPercentEncoding
You only need:
print("Decode: ", yourUrlAsString.removingPercentEncoding)
The stringByReplacingEscapesUsingEncoding method is behaving correctly. The "+" character is not part of percent-encoding. This server is using it incorrectly; it should be using a percent-escaped space here (%20). If, for a particular response, you want spaces where you see "+" characters, you just have to work around the server behavior by performing the substitution yourself, as you are already doing.
It's better to use built-in URLComponents struct, since it follows proper guidelines.
extension URL
{
var parameters: [String: String?]?
{
if let components = URLComponents(url: self, resolvingAgainstBaseURL: false),
let queryItems = components.queryItems
{
var parameters = [String: String?]()
for item in queryItems {
parameters[item.name] = item.value
}
return parameters
} else {
return nil
}
}
}
In my case, I NEED a plus ("+") signal in a phone number in parameters of a query string, like "+55 11 99999-5555". After I discovered that the swift3 (xcode 8.2) encoder don't encode "+" as plus signal, but space, I had to appeal to a workaround after the encode:
Swift 3.0
_strURL = _strURL.replacingOccurrences(of: "+", with: "%2B")
In Swift 3
extension URL {
var parseQueryString: [String: String] {
var results = [String: String]()
if let pairs = self.query?.components(separatedBy: "&"), pairs.count > 0 {
for pair: String in pairs {
if let keyValue = pair.components(separatedBy: "=") as [String]? {
results.updateValue(keyValue[1], forKey: keyValue[0])
}
}
}
return results
}
}
in your code to access below
let parse = url.parseQueryString
print("parse \(parse)" )