How to send a image to a php file using Swift - php

For my app i need to send a image to a php file.
I already know how to send strings using this:
var bodyData = "info=test"
let URL: NSURL = NSURL(string: "LINK TO A PHP FILE")
let request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
And in my php file:
$info = $_POST['info'];
echo $info;
But i don't know how to send a image

var imageData :NSData = UIImageJPEGRepresentation(imagenReduced, 1.0);
var request: NSMutableURLRequest?
let HTTPMethod: String = "POST"
var timeoutInterval: NSTimeInterval = 60
var HTTPShouldHandleCookies: Bool = false
request = NSMutableURLRequest(URL: url)
request!.HTTPMethod = HTTPMethod
request!.timeoutInterval = timeoutInterval
request!.HTTPShouldHandleCookies = HTTPShouldHandleCookies
let boundary = "----------SwIfTeRhTtPrEqUeStBoUnDaRy"
let contentType = "multipart/form-data; boundary=\(boundary)"
request!.setValue(contentType, forHTTPHeaderField:"Content-Type")
var body = NSMutableData();
let tempData = NSMutableData()
let fileName = filenames + ".jpg" //"prueba.jpg"
let parameterName = "userfile"
let mimeType = "application/octet-stream"
tempData.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
let fileNameContentDisposition = fileName != nil ? "filename=\"\(fileName)\"" : ""
let contentDisposition = "Content-Disposition: form-data; name=\"\(parameterName)\"; \(fileNameContentDisposition)\r\n"
tempData.appendData(contentDisposition.dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData("Content-Type: \(mimeType)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
tempData.appendData(imageData)
tempData.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(tempData)
body.appendData("\r\n--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request!.setValue("\(body.length)", forHTTPHeaderField: "Content-Length")
request!.HTTPBody = body
var vl_error :NSErrorPointer = nil
var responseData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil, error:vl_error)
var results = NSString(data:responseData, encoding:NSUTF8StringEncoding)
println("finish \(results)")

//check this code
func callToProfileUpdate()
{
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.labelText = "Loading"
var userID: AnyObject! = NSUserDefaults.standardUserDefaults().valueForKey("USER_ID")
var urlString = NSString(string:"\(baseurl)action=update_profile&user_id=\(userID)&user_name=\(userName.text)&account_type=\(self.selectedAccountTypeLabel.text!)&show_comments=\(commentStauts)&tag_permission=\(tagPermission)")
urlString = urlString .stringByReplacingOccurrencesOfString(" ", withString: "%20")
var url = NSURL(string:urlString as String)
let urlRequest = NSMutableURLRequest(URL: url!)
if mediaData != nil
{
urlRequest.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
urlRequest.addValue(contentType as String, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"photo\"; filename=\".png\"\\.png\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(mediaData)
body.appendData(NSString(format: "\r\n--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
urlRequest.HTTPBody = body
}

Related

Image is not uploaded in PHP using Swift

I am trying to use Google Vision API and upload an image using their API to get analysis. I am using this php code:
<?php
include("./includes/common.php");
include_once("creds.php"); // Get $api_key
$cvurl = "https://vision.googleapis.com/v1/images:annotate?key=" . $api_key;
$type = "LABEL_DETECTION";
//echo "Item is: " . $item;
//Did they upload a file...
$item = $_GET[item];
if($_FILES['photo']['name'])
{
}else{
echo "you did not upload image".
}
It always show "you did not upload image". And here's my Swift function where I upload the image:
func UploadRequest(img: UIImage, item: String)
{
let url = NSURL(string: "http://myurlhere")
let request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
let boundary = generateBoundaryString()
//define the multipart request type
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let image_data = UIImagePNGRepresentation(img)
if(image_data == nil)
{
return
}
let body = NSMutableData()
let fname = "image.png"
let mimetype = "image/png"
//define the data post parameter
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"test\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("hi\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Disposition:form-data; name=\"file\"; filename=\"\(fname)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Content-Type: \(mimetype)\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(image_data!)
body.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("--\(boundary)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
//EZLoadingActivity.hide(success: false, animated: true)
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
//EZLoadingActivity.hide(success: true, animated: true)
self.dismissViewControllerAnimated(true, completion: nil)
}
task.resume()
}
When I do print_r($_FILES), I get:
Array
(
[file] => Array
(
[name] => image.png
[type] => image/png
[tmp_name] => /tmp/phplSB2dc
[error] => 0
[size] => 864781
)
)
Your form data is currently submitting:
body.appendData("Content-Disposition:form-data; name=\"file\";...
And according to your print_r($_FILES), you should be using file instead of photo:
$_FILES['file']['name']
Also, you should be checking to make sure the file uploaded correctly using:
if ( $_FILES['file']['error'] == UPLOAD_ERR_OK )
{
//File uploaded correctly
}
func uploadMultipleIMAGE( APIStriing:NSString, dataString:NSString) -> Void
{
//Here dataString is image binary data just append you your url and just pass the image it will handle.
print("wscall URL string \(APIStriing)")
print("Data string URL string \(dataString)")
let postData = dataString.dataUsingEncoding(NSASCIIStringEncoding, allowLossyConversion: true)!
let postLength = "\(UInt(postData.length))"
let request = NSMutableURLRequest()
request.URL = NSURL(string: APIStriing as String)!
request.HTTPMethod = "POST"
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPBody = postData
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse?,data: NSData?,error: NSError?) -> Void in
if error == nil {
print("success")
}
else {
let alert = UIAlertView(title: "Sorry For Inconvenience ", message: "Contact to Administration", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
})
}
Note:- when you convert image to binary data you need to handle special character. here you can handle special character. follow this step.
1.
let imgData = UIImagePNGRepresentation(image)
imgBase64String = imgData!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
var newimagdat = NSString()
newimagdat = newimagdat.stringByAppendingString(self.percentEscapeString(imgBase64String) as String)
imgarray.addObject(newimagdat)
Create character handler class something like that.
class handlecharacter: NSCharacterSet {
func urlParameterValueCharacterSet() -> NSCharacterSet {
let characterser = NSMutableCharacterSet.alphanumericCharacterSet()
characterser.addCharactersInString("-._~")
return characterser
}
}
Now create function your class where you want to upload images
func percentEscapeString(imgstring:NSString) -> NSString
{
let handle = handlecharacter()
return imgstring.stringByAddingPercentEncodingWithAllowedCharacters(handle.urlParameterValueCharacterSet())!
}

swift 2 character "&" cannot upload in http POST Request

I am trying to send some string to mysql through PHP which the string include some special characters, such as "&,?,/".
The problem is all the string which after the character "&" will be missed.
for example, the string "Ak-47&Bomber" will be send in "Ak-47".
Swift:
let url: NSURL = NSURL(string: "MyPhP.php")!
let session = NSURLSession.sharedSession()
let request:NSMutableURLRequest = NSMutableURLRequest(URL:url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let bodydata = "String=\(Ak-47&Bomber)"
request.HTTPBody = bodydata.dataUsingEncoding(NSUTF8StringEncoding)
if bodydata != " " {
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
PHP :
$String= ($_POST["String"]); // the String i got "Ak-47"
$sql = "INSERT INTO table (string) VALUES ('" .
$String."' )";
$result = mysqli_query($conn, $sql);
any solution?

Request on php script with nsurlconnection

i try to send value to server with this code by i have an error on this line:
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
the error is : EXTRA ARGUMENT IN CALL "error"
var yourUrl="mylink"
let url = NSURL(string:yourUrl)
let cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
var request = NSMutableURLRequest(URL: url!, cachePolicy: cachePolicy, timeoutInterval: 2.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 = "my value"
let requestBodyData = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = requestBodyData
var response: NSURLResponse? = nil
var error: NSError? = nil
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error: &error)
let results = NSString(data:reply!, encoding:NSUTF8StringEncoding)
if let dataFromString = results!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
let json = JSON(data: dataFromString)
if(json=="0"){
print("\n Dati non validi");
}
else{
print("\n Account creato");
}
}
You should never use sendSynchronousRequest as it is a blocking call. Also it is deprecated from iOS 9.0 onwards. Instead you can use NSURLSession. Try out following code
var yourUrl="mylink"
let URL = NSURL(string:yourUrl)
let request:NSMutableURLRequest = NSMutableURLRequest(URL: URL)
let boundaryConstant = "V2ymHFg03esomerandomstuffhbqgZCaKO6jy";
let contentType = "multipart/form-data; boundary=" + boundaryConstant
NSURLProtocol.setProperty(contentType, forKey: "Content-Type", inRequest: request)
var dataString = "my value"
request.HTTPMethod = "POST"
request.HTTPBody = (dataString as NSString).dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
//reponse recieved
//in this case response string will be saved in data, its of type NSData
do{
let str = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [String:AnyObject]
print(str)
}
catch {
print("json error: \(error)")
}
})
task.resume()

IOS SWIFT 2 - Http Post json array to server

I want to send data from my iOS app to a PHP sever in JSON format. I am doing this at the backend with the following code:
$json = $_POST['json'];
$data = json_decode($json, TRUE);
$email = $data['email'];
$user_password = $data['password'];
I want to send data in a JSON variable such that I can accept the data in
the JSON variable and then extract the fields one by one.
At the moment, I am doing this in my iOS app with the following Swift code:
func login(){
let email:NSString = txtEmail.text!
let password:NSString = txtPassword.text!
let post:NSString = "username=\(email)&password=\(password)"
NSLog("PostData: %#",post);
let url:NSURL = NSURL(string:"http://example.com/test.php")!
let postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!
let postLength:NSString = String( postData.length )
let request:NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.HTTPBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: NSURLResponse?
var urlData: NSData?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request, returningResponse:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if ( urlData != nil ) {
let res = response as! NSHTTPURLResponse!;
NSLog("Response code: %ld", res.statusCode);
if (res.statusCode >= 200 && res.statusCode < 300)
{
let responseData:NSString = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!
NSLog("Response ==> %#", responseData);
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(urlData!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary
let success:NSInteger = jsonData!.valueForKey("success") as! NSInteger
NSLog("Success: %ld", success);
} catch let error as NSError {
print(error.localizedDescription)
}
}
}
}
I think I have to send a JSON array, but I don't know how can I save the variables in the array and send the JSON array to the PHP server. Anyone have any ideas?
You can do this by creating an array of dictionaries:
var user_outer_arrary = [[String:Any]]()
var user_inner_array = [String: Any]();
var jsonData : Data? = nil
let user_data :[String:Any]=["email": email,"password": password];
user_outer_arrary.append(user_data);
user_inner_array=["json": user_outer_arrary]
Then convert to JSON:
do
{
jsonData = try JSONSerialization.data(withJSONObject: user_inner_array, options: JSONSerialization.WritingOptions.prettyPrinted)
}
catch
{
}

Saving image on db mysql through swift

i have a problem with my php file.
I'm trying to upload an image through xcode to mysql db.
here's swift code
let image = UIImage(named: "image.jpg")
var imageData = UIImageJPEGRepresentation(image, 1)
if imageData != nil{
var request = NSMutableURLRequest(URL: NSURL(string:"link php file")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%#",boundary)
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Image
body.appendData(NSString(format: "--%#\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: attachment; name=\"userfile\"; filename=\"img.jpg\"").dataUsingEncoding(NSUTF8StringEncoding)!)
//body.appendData(NSString(format: "Content-Type: application/octet-stream\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(imageData)
body.appendData(NSString(format: "\r\n--%#--\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
request.HTTPBody = body
var returnData = NSURLConnection.sendSynchronousRequest(request, returningResponse: nil, error: nil)
var returnString = NSString(data: returnData!, encoding: NSUTF8StringEncoding)
println("returnString \(returnString)")
}
and here's php code:
$myparam = $_FILES['userfile']; //getting image Here //getting textLabe Here
$target_path = "uploads/".basename($myparam['filename']);
if(move_uploaded_file($myparam['tmp_name'], $target_path)){
$var = 1;
}
else {
$var = 0;
}
$myarray = array("response" => $var, "path" => $target_path);
$out = json_encode($myarray);
echo($out);
the problem is in the path. it returns wrong path and so i found no image in "uploads" folder. if i change target_path in php file (for example $target_path = "uploads/image.jpg"), image is saved.
i think it's a very easy problem but i don't understand what i have to change.
thanks for any help
hi

Categories