MySQL — как загрузить изображение в Swift 2 на сервер PHP

Я пытаюсь загрузить фотографии в свою базу данных на моем сервере из приложения для iPhone. я использую быстрый язык 2. пожалуйста, помогите мне. Я прилагаю свой код, чтобы загрузить другие данные в ссылку JSON, и я хочу добавить изображение также к моей ссылке. Помогите мне, пожалуйста

import UIKitclass MealViewController: UIViewController, UITextFieldDelegate,

UIImagePickerControllerDelegate, UINavigationControllerDelegate {

// MARK: Properties

@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
@IBOutlet weak var usernameLabel: UILabel!

override func viewDidLoad() {
super.viewDidLoad()// Handle the text field’s user input through delegate callbacks.
nameTextField.delegate = self

let attributes = [
NSForegroundColorAttributeName: UIColor.blueColor(),
NSFontAttributeName: UIFont(name: "Avenir", size: 2)!
]
self.navigationController?.navigationBar.titleTextAttributes = attributes

}// MARK: UITextFieldDelegate

func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard.
textField.resignFirstResponder()
return true
}

func textFieldDidEndEditing(textField: UITextField) {

}

// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage

// Set photoImageView to display the selected image.
photoImageView.image = selectedImage

print("my image ", photoImageView)

// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}

// MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard.
//nameTextField.resignFirstResponder()

// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()

// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary

// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self

presentViewController(imagePickerController, animated: true, completion: nil)
}

override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)

let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1) {
self.performSegueWithIdentifier("goto_login", sender: self)
} else {
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}@IBAction func ratingSubmitButton(sender: UIButton) {

print(ratingControl.rating)
print(self.usernameLabel.text!)let name:NSString = self.usernameLabel.text!
let value = ratingControl.ratinglet imageData = UIImagePNGRepresentation(photoImageView.image!)do {
let post:NSString = "name=\(name)&value=\(value)"
NSLog("PostData: %@",post);

let url:NSURL = NSURL(string:"http://kiran.com/insert.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);

//var error: NSError?

let jsonData:NSDictionary = try NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionarylet success:NSInteger = jsonData.valueForKey("success") as! NSInteger

//[jsonData[@"success"] integerValue];

NSLog("Success: %ld", success);

if(success == 1)
{
NSLog("Login SUCCESS");

let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(name, forKey: "USERNAME")
prefs.setInteger(1, forKey: "ISLOGGEDIN")
prefs.synchronize()

self.performSegueWithIdentifier("goto_rating", sender: self)
} else {
var error_msg:NSString

if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"}
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Failed"alertView.message = error_msg as String
alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()

}

} else {
}
} else {
}
} catch {
let alertView:UIAlertView = UIAlertView()
alertView.title = "Rating Success!"alertView.message = "Thank You"alertView.delegate = self
alertView.addButtonWithTitle("OK")
alertView.show()
}

}@IBAction func logOutButton(sender: UIButton) {

let appDomain = NSBundle.mainBundle().bundleIdentifier
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain!)

self.performSegueWithIdentifier("goto_login", sender: self)
}

`

1

Решение

Задача ещё не решена.

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]