Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of using NSURLSession
/// Used to interact with the 2k games server API, and upload images to the server
class APIOperations: NSObject, NSURLSessionDelegate {
/** This method is using just a genereic URLSession to upload image to a server
- Parameters:
- Image: image to upload
- imageType: kind of image (2k type) don't confuse it with png/jpg
- callback: callback that contains information about successful or failed operation
*/
static func uploadImage(image:UIImage,token:String, imageType:String, callback:((message:String?, error:String?)->Void))->NSURLSessionTask{
var imageData = UIImagePNGRepresentation(image)
imageData = NSData(data: imageData)
var request = NSMutableURLRequest(URL: NSURL(string:APIKeys.url.rawValue)!)
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
// var session = NSURLSession.sharedSession()
var sessionConfig = NSURLSessionConfiguration.defaultSessionConfiguration()
var authorizationString = "\(APIKeys.kUsername.rawValue):\(APIKeys.kPassword.rawValue)"
var authorizationData = authorizationString.dataUsingEncoding(NSUTF8StringEncoding)
//Authorization header
var authHeader = "Basic \(authorizationData)"
var authHeaderData = authHeader.dataUsingEncoding(NSUTF8StringEncoding)
sessionConfig.HTTPAdditionalHeaders = ["Authorization":authHeader]
let delegate = SessionDelegate()
var session = NSURLSession(configuration: sessionConfig, delegate: delegate, delegateQueue: NSOperationQueue.mainQueue())
request.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
// println("Content Type \(contentType)")
request.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Add
body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"add\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Test".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
// Image Type
body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"content_type\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageType.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
// Token
body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"tok\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(token.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
//Other fields
// Image Content-Transfer-Encoding: binary
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"image\"; filename=\"img\(NSDate()).png\"\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: image/png\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
// session.uploadTaskWithRequest(request, fromData: body)
// NSURLSessionUploadTask()
let task = session.uploadTaskWithRequest(request, fromData: body, completionHandler: { (data, response, error) -> Void in
var returnString:String?
if let data = data, string = NSString(data: data, encoding: NSUTF8StringEncoding) {
returnString = string as String
}
var errorText:String?
if let error = error{
errorText = error.description
}
callback(message: returnString, error: errorText)
})
task.resume()
return task
}
}
/// Used to deal with the 2k server authentication challenge
class SessionDelegate: NSObject, NSURLSessionDelegate{
func URLSession(session: NSURLSession, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)
{
let credentials = NSURLCredential(user: APIKeys.kUsername.rawValue, password: APIKeys.kPassword.rawValue, persistence: NSURLCredentialPersistence.Permanent)
if challenge.previousFailureCount > 0 {
println("Failure count: \(challenge.previousFailureCount)")
}
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential, credentials)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!){
println("task-didReceiveChallenge")
if challenge.previousFailureCount > 0 {
println("Alert Please check the credential")
completionHandler(NSURLSessionAuthChallengeDisposition.CancelAuthenticationChallenge, nil)
} else {
let credentials = NSURLCredential(user: APIKeys.kUsername.rawValue, password: APIKeys.kPassword.rawValue, persistence: NSURLCredentialPersistence.Permanent)
completionHandler(NSURLSessionAuthChallengeDisposition.UseCredential,credentials)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.