我正在尝试将图片上传到服务器。图片在达到80%后开始上传。我收到了这个错误:
GET错误域= NSURLErrorDomain代码= -1004"无法连接到 。服务器#&34;的UserInfo = {NSUnderlyingError = 0x7fcb0e1de350
它还显示:
NSErrorFailingURLStringKey=http://apiurl/api/orders/372/images/6,
NSErrorFailingURLKey=http://apiurl/api/orders/372/images/6,
这是什么意思?请帮忙,我已经花了3天时间找到解决方案。
答案 0 :(得分:0)
这是我的解决方案。我处理了图片的上传,并且遇到了很多麻烦,直到我找到了一个解决方案(有些东西是葡萄牙语,但这不是问题)。
我的代码:
//
// PostarViewController.swift
// AppOnTheLine
//
// Created by Elson Costa on 17/08/16.
// Copyright © 2016 Elson Costa. All rights reserved.
//
import UIKit
extension NSMutableData {
func appendString(string: String) {
let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
appendData(data!)
}
}
class PostarViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
@IBOutlet var btnSelecionar: UIButton!
@IBOutlet var imgPost: UIImageView!
@IBOutlet var txtDescricao: UITextField!
@IBOutlet var lblEnviando: UILabel!
var myActivityIndicator = UIActivityIndicatorView()
override func viewDidLoad() {
super.viewDidLoad()
iniciarComponentes()
}
func iniciarComponentes(){
myActivityIndicator = UIActivityIndicatorView(frame: CGRectMake(0,0,50,50))
myActivityIndicator.center = self.view.center
myActivityIndicator.hidesWhenStopped = true
myActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
self.view.addSubview(myActivityIndicator)
}
@IBAction func selecionarImg(sender: AnyObject) {
selectType(0)
}
@IBAction func tirarFoto(sender: AnyObject) {
selectType(1)
}
func selectType(tipo:Int){
let image = UIImagePickerController()
image.delegate = self
if tipo == 0 {
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}else{
image.sourceType = UIImagePickerControllerSourceType.Camera
}
image.allowsEditing = false
self.presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
imgPost.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData()
if parameters != nil {
for (key, value) in parameters! {
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
let filename = "myImage.jpg"
let mimetype = "image/jpg"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(imageDataKey)
body.appendString("\r\n")
body.appendString("--\(boundary)--\r\n")
return body
}
@IBAction func enviarPost(sender: AnyObject) {
activityInSwitch(true)
if imgPost.image != nil && txtDescricao.text != "" {
lblEnviando.hidden = false
let urlWBS = NSURL(string:"myserver.com/salvar_post.php")! //HERE YOU PUT YOUR SERVER LINK!
let request = NSMutableURLRequest(URL:urlWBS);
request.HTTPMethod = "POST"
let param = [
"user" : "\(usuario.getId())",
"post" : "\(txtDescricao.text!)"
]
let boundary = "Boundary-\(NSUUID().UUIDString)"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(imgPost.image!, 1)
if imageData == nil { return }
request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData!, boundary: boundary)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
if(error != nil){
print("error = \(error!)")
self.lblEnviando.hidden = true
self.exibirAlert("Aconteceu um erro!", msg:"Por favor, tente novamente!", nameBtn:"Continuar")
return
}
do{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let result = myJSON!["success"] as! String
if (result == "1"){
self.activityInSwitch(false)
self.txtDescricao.text = ""
self.imgPost.image = UIImage(named: "placeholder.png")
self.lblEnviando.hidden = true
self.exibirAlert("Post Enviado", msg:"Seu post foi enviado com sucesso!", nameBtn:"OK")
}else{
self.activityInSwitch(false)
self.lblEnviando.hidden = true
self.exibirAlert("Aconteceu um Erro", msg:"\(myJSON!["message"])", nameBtn:"Continuar")
}
})
}catch{
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.activityInSwitch(false)
self.lblEnviando.hidden = true
self.exibirAlert("Aconteceu um erro!", msg:"Por favor, tente novamente!", nameBtn:"Continuar")
})
}
}
task.resume()
}else{
self.activityInSwitch(false)
self.lblEnviando.hidden = true
self.exibirAlert("Verificar Campos", msg:"Verifique os campos!", nameBtn:"Continuar")
}
}
func activityInSwitch(ligar:Bool){
if (ligar){
self.myActivityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}else{
self.myActivityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
}
func exibirAlert(titleAlert: String, msg: String, nameBtn:String){
let alert = UIAlertController(title: titleAlert, message: msg, preferredStyle:UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: nameBtn, style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
现在,我的php文件(salvar_post.php):
<?php
include_once("Conexao.php");
try{
if(!$conectou){
//nfpc: Não foi possível conectar
throw new Exception("nfpc");
}
if (!isset($_POST['user']) && !isset($_POST['post']) && !isset($_FILES['file']['name'])) {
//dnp: Dados não Preenchidos
throw new Exception("dnp");
}
$user = $_POST["user"];
$text = $_POST["post"];
$data_hora_post = date('d/m/Y') . " às " . date('H:i:s');
$nome_imagem = $_FILES['file']['name'];
$ext = strtolower(strrchr($nome_imagem, "."));
$imageName = "img_post_" . date('YmdHis') . $ext;
$target_dir = "imagens";
if(!file_exists($target_dir)){
mkdir($target_dir, 0777);
}
$target_dir = $target_dir . "/" . $imageName;
if (move_uploaded_file($_FILES['file']['tmp_name'], $target_dir)){
$resultQuery = mysql_query("INSERT INTO tb_post(id_user, text_post, data_hora_post, image) VALUES ('{$user}', '{$text}', '{$data_hora_post}', '{$imageName}');");
if ($resultQuery){
$response["success"] = "1";
$response["message"] = "O post foi salvo e imagem enviada com sucesso!";
echo json_encode($response);
}else{
//Não foi possivel salvar o post
throw new Exception("nfpsp");
}
}else{
//Não salvou a imagem
throw new Exception("nsai");
}
}catch(Exception $ex){
$response = array();
switch ($ex->getMessage())
{
case 'nfpc':
$response["success"] = "0";
$response["message"] = "Não foi possivel conectar. ERROR: " . mysql_error();
break;
case 'dnp':
$response["success"] = "0";
$response["message"] = "Dados não preenchidos. ERROR: " . mysql_error();
break;
case 'nsai':
$response["success"] = "0";
$response["message"] = "Não foi possível salvar a imagem.";
break;
case 'nfpsp':
$response["success"] = "0";
$response["message"] = "Não foi possível salvar o post.";
break;
default:
break;
}
echo json_encode($response);
}?>