Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Michael Voccola
1,758 PointsPass date in URL for PHP request using Swift
I have a swift project that connects to a PHP service which returns data in JSON format. One of the requests requires two timestamps be passed in the URL. The app calculates inventory availability for a given date range, so these are user-generated dates and times in the following format:
"1/15/2015 16:00"
When testing the PHP file in a browser and manually injecting the parameters, the desired URL is as follows:
http://localhost/php/FM_ScriptReturnTest.php?barcode=2010&start=10/1/2014 8:00 AM&end=10/5/2014 4:00 PM
The results are returned correctly. However, when generating a URL in Swift containing these time/date variables using println(url: (url)) returns:
url: nil
And of course, the solution doesn't work if the URL has no value. I suspect is has something to do with the slashes in the date, is there any way around this?
1 Answer
Michael Voccola
1,758 PointsSolved:
'''swift
class func scanItemOutInfo (barcode:String) -> NSDictionary {
//direct to php file location
let server:String = GlobalVars.serverAddress
let companyId:String = GlobalVars.currentCompanyId
let start:String = GlobalVars.currentJobStart as String!
let end:String = GlobalVars.currentJobEnd as String!
let startEncoded = start.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let endEncoded = end.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
let phpFile:String = "/php/FM_ScriptReturnTest.php"
let baseURL = NSURL(string: "http://\(server)\(phpFile)")
let url = NSURL(string: "?barcode=\(barcode)&start=\(startEncoded)&end=\(endEncoded)", relativeToURL: baseURL)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 20.0)
request.HTTPMethod = "POST"
//set Content-Type in HTTP header
//let boundaryConstant = "----------V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
//let contentType = "multipart/form-data; boundary=" + boundaryConstant
//NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
// set data
var dataString = ""
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
// set content length
//NSURLProtocol.setProperty(requestBodyData.length, forKey: "Content-Length", inRequest: request)
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply: NSData! = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
//Parse JSON results
var jsonerror:NSError?
let swiftObject:AnyObject = NSJSONSerialization.JSONObjectWithData(reply, options: NSJSONReadingOptions.AllowFragments, error:&jsonerror)!
let nsArrayObject:NSDictionary = swiftObject as NSDictionary
let itemDict:Dictionary = nsArrayObject as Dictionary
println("Dictionary: \(itemDict)")
return itemDict
}
'''