Skip to content

Instantly share code, notes, and snippets.

@pokk
Last active October 21, 2016 07:56
Show Gist options
  • Save pokk/e94f1d5741a7abc88d71b622d5d9f649 to your computer and use it in GitHub Desktop.
Save pokk/e94f1d5741a7abc88d71b622d5d9f649 to your computer and use it in GitHub Desktop.
send pictures to php server by Alamofire library

Introduction

Send a media file to php server from swift.

<?php
public function post_picture()
{
// This is get the file from FILES
// 'picture' is consistent in Alamofire 'name' parameter.
// 'beautifulimage' is consistent in Alamofire 'fileName' parameter.
$pictureFromClient = $_FILES['picture']['beautifulimage'];
return array(
'status' => Conf_Api_Statuscode::OK
);
}
// The is override from UIImagePickerControllerDelegate
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String: AnyObject]) {
// Check the img you picked.
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
// Here is using Alamofire to send to php server.
// Image what you want to send.
let imageData = NSData(data: UIImagePNGRepresentation(image)!)
// Parameters for post request
let parameters = ["parameter1": "para", "parameter2": "para"]
Alamofire.upload(.POST,
"http://www.test.com",
multipartFormData: {
multipartFormData in
// For file or img or media.
multipartFormData.appendBodyPart(data: imageData, name: "picture", fileName: "beautifulimage", mimeType: "image/jpg")
// For post parameters.
for (key, value) in parameters {
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
}
},
encodingCompletion: {
encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.responseJSON {
response in
print(response)
}
case .Failure(let encodingError):
print(encodingError)
}
})
}
dismissViewControllerAnimated(true, completion: nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment