我在Amazon AWS上传图片时遇到问题。这是我的代码:
import UIKit
protocol ContentUploaderDelegate {
func onContentLoadComplete(status:Bool,serverResponse:String)
}
class ContentUploader
{
let contentURL = "https:<MY URL>amazonaws.com/api/v1/contents"
var delegate:ContentUploaderDelegate?
func uploadImage(image:UIImage,xAuth:String,mimeType:String,imageName:String)
{
let url = NSURL(string: contentURL)
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")
request.setValue(xAuth, forHTTPHeaderField: "x-auth-token")
request.setValue("application/json", forHTTPHeaderField: "accept")
let image_data = UIImageJPEGRepresentation(image, 1.0)
if(image_data == nil)
{
return
}
let body = NSMutableData()
//name to save in server
let fname = imageName
let mimetype = mimeType
//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=\"files\"; 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)!)
//set the HTTPBody
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 {
print("error")
self.delegate?.onContentLoadComplete(false, serverResponse: (error?.description)!)
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("success \(dataString)")
self.delegate?.onContentLoadComplete(true, serverResponse:dataString! as String)
}
task.resume()
}
private func generateBoundaryString() -> String
{
return "Boundary-\(NSUUID().UUIDString)"
}
永远不会调用以下委托方法。可能是什么原因?
func URLSession(session: NSURLSession,
task: NSURLSessionTask,
didReceiveChallenge challenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?)
-> Void) {
let protectionSpace = challenge.protectionSpace
let theSender = challenge.sender
if protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
if (challenge.protectionSpace.host == "ec2-52-36-216-81.us-west-2.compute.amazonaws.com") {
if let theTrust = protectionSpace.serverTrust{
let theCredential = NSURLCredential(trust: theTrust)
theSender!.useCredential(theCredential, forAuthenticationChallenge: challenge)
return
}
}
}
theSender!.performDefaultHandlingForAuthenticationChallenge!(challenge)
return
}
}
我收到以下错误消息。知道为什么会出现这个错误吗?
错误域= NSURLErrorDomain代码= -1202“此证书 服务器无效。您可能正在连接到的服务器 假装是“.amazonaws.com”,可以把你的 有风险的机密信息。“ UserInfo = {NSURLErrorFailingURLPeerTrustErrorKey =,NSLocalizedRecoverySuggestion =你想要吗? 无论如何连接到服务器?,_kCFStreamErrorDomainKey = 3, _kCFStreamErrorCodeKey = -9813,NSErrorPeerCertificateChainKey = {type = immutable,count = 1,values =( 0:.com i:www..com&gt; ),NSUnderlyingError = 0x7f9d42aedc10 {错误 Domain = kCFErrorDomainCFNetwork Code = -1202“(null)” 的UserInfo = {_ kCFStreamPropertySSLClientCertificateState = 0, kCFStreamPropertySSLPeerTrust =, _kCFNetworkCFStreamSSLErrorOriginalValue = -9813,_kCFStreamErrorDomainKey = 3,_kCFStreamErrorCodeKey = -9813,kCFStreamPropertySSLPeerCertificates = {type = immutable,count = 1,values =( 0:.com i:www..com&gt; )},},NSLocalizedDescription =此服务器的证书是 无效。您可能正在连接到假装的服务器 “.amazonaws.com”可以提供您的机密信息 风险很大。,NSErrorFailingURLKey = https://amazonaws.com/api/v1/contents, NSErrorFailingURLStringKey = HTTPS://.amazonaws.com/api/v1/contents, NSErrorClientCertificateStateKey = 0}
答案 0 :(得分:0)
Error Domain=NSURLErrorDomain Code=-1202 "The certificate for this server is invalid. You might be connecting to a server that is pretending to be “.amazonaws.com”
我认为通用名称“有问题。”amazonaws.com“
NSErrorFailingURLKey=https://amazonaws.com/api/v1/contents,
NSErrorFailingURLStringKey=https://.amazonaws.com/api/v1/contents
错误消息中显示的URL似乎不是众所周知的端点。我希望在那里看到类似https://ec2-2-2-2-2.compute-1.amazonaws.com
或其他完全合格域名的内容。
错误消息也证实了这一点。您正在连接主机,但证书上的名称不匹配。这就是pretending to be “.amazonaws.com”
错误的原因。
确认正确的端点,以及您的代码如何形成完整的网址。
永远不会调用以下委托方法。可能是什么 原因是什么?
在调用函数之前发生错误。由于证书错误,永远不会建立会话。