在 Swift 2.0 中从 iOS 应用程序上传图像到服务器
Posted
技术标签:
【中文标题】在 Swift 2.0 中从 iOS 应用程序上传图像到服务器【英文标题】:Uploading Image to server from iOS Application in Swift 2.0 【发布时间】:2015-10-07 14:34:19 【问题描述】:我正在开发一个 ios 应用程序,我必须将图像上传到服务器,我正在使用 swift 2.0。 下面是代码:
var tempImage:UIImage = info[UIImagePickerControllerOriginalImage] as! UIImage myImage.image = tempImage
print(tempImage)
print([info])
myImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismissViewControllerAnimated(true, completion: nil)
var imageData = UIImagePNGRepresentation(tempImage)
// converting in base64
let base64 = imageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength) as! AnyObject
let url = NSURL(string: "www.google.com/myimage1/PNG")!
let urlRequest = NSMutableURLRequest(URL: url)
urlRequest.HTTPMethod = "POST"
// Set the HTTP Body with the POST data
let postDict = ["encodedImage": base64]
urlRequest.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(postDict , options: [])
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.timeoutInterval = 600
urlRequest.HTTPShouldHandleCookies = false
// urlRequest.setValue("application/json)", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest)
data, response, error in
if error != nil
print("error=\(error)")
return
print("response = \(response)")
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
task.resume()
但我还没有成功。我仍然收到以下错误响应。
error=Optional(Error Domain=NSURLErrorDomain Code=-1001 "请求 超时。” UserInfo=NSUnderlyingError=0x7fad5af61e20 错误 域=kCFErrorDomainCFNetwork 代码=-1001 "(null)" UserInfo=_kCFStreamErrorCodeKey=60, _kCFStreamErrorDomainKey=1, NSErrorFailingURLStringKey=www.google.com/myimage1/PNG, NSErrorFailingURLKey=http://www.google.com/myimage1/PNG, _kCFStreamErrorDomainKey=1, _kCFStreamErrorCodeKey=60, NSLocalizedDescription=请求超时。)
如果您已经在 swift 2.0 中的应用程序中将图像上传到服务器上,请帮帮我。
【问题讨论】:
【参考方案1】:你需要改变你的文件
info.plist
,并使用应用程序 TextEdit 添加此内容,或使用 xcode。
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
</dict>
来自 Xcode http://i.stack.imgur.com/tGsEK.png
,别忘了清理项目。 (cmd + shift + k)
【讨论】:
谢谢!!完美运行!【参考方案2】:func uploadImageOne()
var imageData = UIImagePNGRepresentation(imageView.image)
if imageData != nil
var request = NSMutableURLRequest(URL: NSURL(string:"= Enter your image URL")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var boundary = NSString(format: "---------------------------14737809831466499882746641449")
var contentType = NSString(format: "multipart/form-data; boundary=%@",boundary)
// println("Content Type \(contentType)")
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
var body = NSMutableData.alloc()
// Title
body.appendData(NSString(format: "\r\n--%@\r\n",boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"title\"\r\n\r\n").dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData("Hello World".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
// Image
body.appendData(NSString(format: "\r\n--%@\r\n", boundary).dataUsingEncoding(NSUTF8StringEncoding)!)
body.appendData(NSString(format:"Content-Disposition: form-data; name=\"profile_img\"; filename=\"img.jpg\"\\r\n").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)")
【讨论】:
以上是关于在 Swift 2.0 中从 iOS 应用程序上传图像到服务器的主要内容,如果未能解决你的问题,请参考以下文章
无效的 Swift 支持 - 适用于 iOS 9 的 Swift 2.0 项目,(Xcode build 7A220)