How can a value such as "1.5" be passed in a a URL POST request using swift?
For example:
let number = "1.5"
let numberValue = number.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let server:String = "www.someserver.com"
let phpFile:String = "/php/SomePHPScript.php"
let baseURL = NSURL(string: "http://\(server)\(phpFile)")
let url = NSURL(string: "?value=\(numberValue)", relativeToURL: baseURL)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 10.0)
request.HTTPMethod = "POST"
var dataString = ""
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// etc...
This compiles fine but crashes on execution. It seems converting this to JSON would fix it, but is there cleaner way?
EDIT
stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) returns optional. It needed to be unwrapped.
stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) returns optional. It needed to be unwrapped.
Related
I'm getting an error while trying to use this code:
func getRawJSON(method: String, paramether: String) {
let publicKey = "publicKeyHere"
let secretKey = "secretKeyHere
let APIURL = "https://www.bitmarket.pl/api2/"
let time = String(Int(NSDate().timeIntervalSince1970))
let query = NSURLComponents()
query.queryItems = [NSURLQueryItem(name: "method", value: method) as URLQueryItem,
NSURLQueryItem(name: "tonce", value: time) as URLQueryItem]
let requestString = query.query!
let requestData = Array(requestString.utf8)
let params = [
"method": method,
"tonce:": time
]
let hmac: Array<UInt8> = try! HMAC(key: secretKey.utf8.map({$0}), variant: .sha512).authenticate(requestData)
let hmacString = hmac.map{String(format: "%02X", $0)}.joined(separator: "").lowercased()
let URL = NSURL(string: APIURL)!
let mutableURLRequest = NSMutableURLRequest(url: URL as URL)
mutableURLRequest.httpMethod = "POST"
do {
mutableURLRequest.httpBody = try JSONSerialization.data(withJSONObject: paramether, options: JSONSerialization.WritingOptions())
} catch {
}
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue(publicKey, forHTTPHeaderField: "API-Key")
mutableURLRequest.setValue(hmacString, forHTTPHeaderField: "API-Hash")
Alamofire.request(mutableURLRequest) //Here is a problem
}
Here is the error:
Argument type 'NSMutableURLRequest' does not conform to expected type 'URLRequestConvertible'
What am I doing wrong? Alamofire documentation says NSMutableURLRequest could conform to URLRequestConvertible.
Swift 3 defines URLRequest which conforms to the protocol URLRequestConvertible. You should use URLRequest instead of NSMutableURLRequest.
Refer to this discussion.
I'm trying to use the below code but it doesn't work! Any Idea
let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieHeaderField = ["Cookie": self.CookieValue] // var CookieValue = String()
let url = URL
let parameters = ""
let postData:NSData = parameters.dataUsingEncoding(NSASCIIStringEncoding)!
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: NSURL(string: url)!)
jar.setCookies(cookies, forURL: NSURL(string: url), mainDocumentURL: NSURL(string: url))
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "POST"
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
try this for setting cookies and for better usage understanding.
Below is the swift part for setting up cookie.
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(response.allHeaderFields as NSDictionary as! [String : String], forURL: response.URL!)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookies(cookies, forURL: response.URL!, mainDocumentURL: nil)
I'm trying to set cookie in my HTTP request
and I thought that below code would work:
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
request.setValue("key=value;", forHTTPHeaderField: "Cookie")
but this code is not working.
does anyone have idea how to set it?
Updated answer for Swift 3
You want to look at HTTPCookieStorage.
// First
let jar = HTTPCookieStorage.shared
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = HTTPCookie.cookies(withResponseHeaderFields: cookieHeaderField, for: url)
jar.setCookies(cookies, for: url, mainDocumentURL: url)
// Then
var request = URLRequest(url: url)
Original answer for swift 2
You want to look at NSHTTPCookieStorage.
// First
let jar = NSHTTPCookieStorage.sharedHTTPCookieStorage()
let cookieHeaderField = ["Set-Cookie": "key=value"] // Or ["Set-Cookie": "key=value, key2=value2"] for multiple cookies
let cookies = NSHTTPCookie.cookiesWithResponseHeaderFields(cookieHeaderField, forURL: url)
jar.setCookies(cookies, forURL: url, mainDocumentURL: url)
// Then
let request = NSMutableURLRequest(URL: url)
Swift 5
if let cookie = HTTPCookie(properties: [
.domain: ".my.domain.name.com",
.path: "/",
.name: "myCookieNameKey",
.value: "K324klj23KLJKH223423CookieValueDSFLJ234",
.secure: "FALSE",
.discard: "TRUE"
]) {
HTTPCookieStorage.shared.setCookie(cookie)
print("Cookie inserted: \(cookie)")
}
This may be useful for some one(Swift 5).
Avoid using NSMutableURLRequest in Swift. Instead follow the below snippet:
func request(with url: URL) -> URLRequest {
var request = URLRequest(url: url)
guard let cookies = HTTPCookieStorage.shared.cookies(for: url) else {
return request
}
request.allHTTPHeaderFields = HTTPCookie.requestHeaderFields(with: cookies)
return request
}
Here is how it works in Swift 3.x after you set cookie using HTTPCookieStorage
let cookies=HTTPCookieStorage.shared.cookies(for: URL(string: cookieURL)!)
let headers=HTTPCookie.requestHeaderFields(with: cookies!)
let request = NSMutableURLRequest(url: requestURL!)
request.allHTTPHeaderFields=headers
Before the Swift 2.0 Update this code worked perfectly to download my JSON File from the Server with a PHP Script:
let url = NSURL(string: webAdress)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
After the Update Xcode asked me to do some changes. I did and the code had no Error, but it always throws...
let url = NSURL(string: webAdress)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
let request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 5.0)
var response: NSURLResponse? = nil
var reply = NSData()
do {
reply = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch {
print("ERROR")
}
Looking forward to your solutions!
Here's an example using the new NSURLSession - apparently NSURLConnection has been deprecated in iOS 9.
let url = NSURL(string: webAddress)
let request = NSURLRequest(URL: url!, cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 5.0)
let session = NSURLSession.sharedSession()
session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
print(data)
print(response)
print(error)
})?.resume()
I think it's super clean, there's just not much documentation on it. Let me know if you have any trouble getting this to work.
Maximilian hi,
I have the same unsolved issue, the proposed solution by Sidetalker using NSURLSession.dataTaskWithRequest is not what you looking for since the NSURLSession API is highly asynchronous (according with Apple documentation) and the code you had implemented in swift 1.2 was synchronous.
in the other hand, NSURLConnection has been deprecated in iOS 9 therefore the code you wrote is probably not building, right?
my suggested solution is:
let url = NSURL(string: webAdress)
let request: NSURLRequest = NSURLRequest(URL: url!)
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
let session = NSURLSession(configuration: config)
var responseCode = -1
let group = dispatch_group_create()
dispatch_group_enter(group)
session.dataTaskWithRequest(request, completionHandler: {(_, response, _) in
if let httpResponse = response as? NSHTTPURLResponse {
responseCode = httpResponse.statusCode
}
dispatch_group_leave(group)
})!.resume()
dispatch_group_wait(group, DISPATCH_TIME_FOREVER)
//rest of your code...
please let me know if its now OK
I want to display the data from this URL:
http://www.football-data.org/soccerseasons/351/fixtures?timeFrame=n14
My baseURL is let baseUrl = NSURL(string: "http://www.football-data.org")!,
so my request is let request = NSMutableURLRequest(URL: baseUrl.URLByAppendingPathComponent("soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14"))
But the ?timeFrame=n14 doesn't work.
Anyone knows how to solve this so I can display that data?
The problem is that the question mark in ?timeFrame=n14 is treated as part of the URL's
path and therefore HTML-escaped as %3F. This should work:
let baseUrl = NSURL(string: "http://www.football-data.org")!
let url = NSURL(string: "soccerseasons/" + "\(league.id)" + "/fixtures?timeFrame=n14", relativeToURL:baseUrl)!
let request = NSMutableURLRequest(URL: url)
Alternatively, use NSURLComponents, which lets you build an URL successively from individual components (error checking omitted for brevity):
let urlComponents = NSURLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"
let url = urlComponents.URL!
let request = NSMutableURLRequest(URL: url)
Update for Swift 3:
var urlComponents = URLComponents(string: "http://www.football-data.org")!
urlComponents.path = "/soccerseasons/" + "\(league.id)" + "/fixtures"
urlComponents.query = "timeFrame=n14"
let url = urlComponents.url!
var request = URLRequest(url: url)