2
我對iOS和swift一般很新,希望有人可以幫忙。我正在嘗試創建一個非常簡單的swift iOS應用程序,它將使用多個參數完成一個HTTP帖子,其中一個是圖像或音頻文件。如果你看到一個,請提出更好的方法,但這僅僅是一個概念證明。很明顯,我發佈的是這樣的,它不適用於我的swift應用程序,但我已經能夠通過其他方式使PHP Web服務工作(即「Rest Client」ios應用程序)。Swift iOS發佈文件作爲參數到PHP Webservice
func uploadFile(filename:String) {
println("uploading \(filename)")
var docsDir = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
var url = NSURL(fileURLWithPath: docsDir + "/" + filename)
var request = NSMutableURLRequest(URL: NSURL(string: "http://www.somewebsite.com/testWS.php"))
var audioData :NSData = NSData.dataWithContentsOfURL(url,options: NSDataReadingOptions.DataReadingMappedIfSafe,error: nil)
var bodyData: String = "filenames=Tesing123&userfile=\(audioData)"
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue())
{
(response, data, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
}
}
我的PHP Web服務是:提前
<?php
$myparam = $_POST['userfile']; //getting image Here
$mytextLabel= $_POST['filenames']; //getting textLabe Here
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['userfile']['tmp_name']);
echo basename($_FILES['userfile']['name']);
echo $_POST['userfile'];
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {
echo "The file ". basename($_FILES['userfile']['name']) . " has been uploaded";
} else {
echo "!!!!!There was an error uploading the file, please try again!";
}
?>
感謝。
您還需要查看製作'multipart/form-data'的帖子。有關示例,請參閱[使用NSURLCONNECTION在SWIFT中發佈到WEB服務器API](http://www.brianjcoleman.com/tutorial-post-to-web-server-api-in-swift-using-nsurlconnection/)。 – 2014-10-28 21:36:57