[英]Alamofire keeps getting cancelled
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
var window: UIWindow?
var manager1: SessionManager?
var manager2: SessionManager?
let commons:Commons = Commons()
var selected = 0
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return true
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func uploade()
{
if(selected == 0)
{
let realm = try! Realm()
let uploadAuditInfo = realm.objects(UploadAudit.self)
var uploadAudit = [UploadAudit]()
let uploadDistInfo = realm.objects(UploadData.self)
var uploadDist = [UploadData]()
for i in 0 ..< uploadAuditInfo.count {
if let result = uploadAuditInfo[i] as? UploadAudit {
uploadAudit.append(result)
}
}
for i in 0 ..< uploadDistInfo.count {
if let result = uploadDistInfo[i] as? UploadData {
uploadDist.append(result)
}
}
if(uploadAudit.count > 0)
{
selected = 1
let upload = uploadAudit[0]
let fileNameToDelete = upload.fileName
var filePath = ""
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
} else {
return
}
let lang = self.commons.getLanguage()
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath)
{
let image = UIImage(contentsOfFile: filePath)
let ids = upload.id
let params = upload.params
let name1 = upload.fileName
let url = self.commons.getUrl()
let vas1 = lang+params
let vas2 = url+"rest/secure/"+String(ids)+"/submit?language="
let vas = vas2+vas1
print("upload audit111")
uploadFile(fileName: name1, mimeType:"application/octed-stream", image: image!, url:vas, id: ids)
}
else
{
try! realm.write {
realm.delete(upload)
}
selected = 0
self.uploade()
}
}
else if(uploadDist.count > 0)
{
selected = 1
let upload = uploadDist[0]
let fileNameToDelete = upload.fileName
var filePath = ""
let dirs : [String] = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true)
if dirs.count > 0 {
let dir = dirs[0] //documents directory
filePath = dir.appendingFormat("/" + fileNameToDelete)
} else {
return
}
let fileManager = FileManager.default
if fileManager.fileExists(atPath: filePath)
{
let lang = self.commons.getLanguage()
let image = UIImage(contentsOfFile: filePath)
let ids = upload.id
let params = upload.params
let name1 = upload.fileName
let url = self.commons.getUrl()
let vas1 = lang+params
let vas2 = url+"rest/secure/another/"+String(ids)+"/submit?language="
let vas = vas2+vas1
print("upload dist111")
uploadFileDist(fileName: name1, mimeType:"application/octed-stream", image: image!, url:vas, id: ids)
}
else
{
try! realm.write {
realm.delete(upload)
}
selected = 0
self.uploade()
}
}
else
{
}}
else
{
}
}
func uploadFileDist(fileName: String, mimeType: String, image: UIImage, url: String, id: Int )
{
let preferences = UserDefaults.standard
//NSUserDefaults.standardUserDefaults()
let currentLevelKey = "sessionId"
if UserDefaults.standard.object(forKey: currentLevelKey) == nil {
} else {
let name = preferences.string(forKey: currentLevelKey)
DispatchQueue.global().async {
let sessionName = "JSESSIONID="+name!
// get headers
let headers = self.commons.getHeader(cookie: sessionName)
// get language
// get configuration
let configuration = self.commons.getConfiguration(timeout: 600)
self.manager2 = Alamofire.SessionManager(configuration: configuration)
// get base url
let image_data = UIImageJPEGRepresentation(image, 0.4)
let uuid = UUID().uuidString
let uuid2 = UUID().uuidString
let nameOfImage = "profile-"+uuid+"--"+uuid2
print("dist upload")
self.manager2!.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(image_data!, withName: "uploadFile", fileName: nameOfImage+".jpeg", mimeType: mimeType)
}, to: url, method: .post, headers: headers, encodingCompletion: { (result) in
//self.manager1!.session.invalidateAndCancel()
print("dist result")
switch result {
case .success( let upload , _, _):
upload.responseObject(keyPath: ""){ (response: DataResponse<User>) in
let realm = try! Realm()
let ps = "id == "+String(id)
let datas = realm.objects(UploadData.self).filter(ps)
let datas2 = realm.objects(DistRealM.self).filter(ps)
try! realm.write {
realm.delete(datas)
realm.delete(datas2)
}
self.selected = 0
self.uploade()
}
case .failure( _):
self.selected = 0
}
})
}
}
}
func uploadFile(fileName: String, mimeType: String, image: UIImage, url: String, id: Int )
{
let preferences = UserDefaults.standard
//NSUserDefaults.standardUserDefaults()
let currentLevelKey = "sessionId"
if UserDefaults.standard.object(forKey: currentLevelKey) == nil {
} else {
let name = preferences.string(forKey: currentLevelKey)
DispatchQueue.global().async {
// set session cookie
let sessionName = "JSESSIONID="+name!
// get headers
let headers = self.commons.getHeader(cookie: sessionName)
// get language
// get configuration
let configuration = self.commons.getConfiguration(timeout: 600)
self.manager2 = Alamofire.SessionManager(configuration: configuration)
// get base url
print(" audit upload ")
let image_data = UIImageJPEGRepresentation(image, 0.4)
let uuid = UUID().uuidString
let uuid2 = UUID().uuidString
let nameOfImage = "profile-"+uuid+"--"+uuid2
self.manager2!.upload(multipartFormData: { (MultipartFormData) in
MultipartFormData.append(image_data!, withName: "uploadFile", fileName: nameOfImage+".jpeg", mimeType: mimeType)
}, to: url, method: .post, headers: headers, encodingCompletion: { (result) in
// self.manager1!.session.invalidateAndCancel()
print("audit result")
switch result {
case .success( let upload, _, _):
upload.responseObject(keyPath: ""){ (response: DataResponse<User>) in
debugPrint(response)
let realm = try! Realm()
let ps = "id == "+String(id)
let datas = realm.objects(UploadAudit.self).filter(ps)
let datas2 = realm.objects(AuditRealM.self).filter(ps)
try! realm.write {
realm.delete(datas)
realm.delete(datas2)
}
self.selected = 0
self.uploade()
}
case .failure( _):
self.selected = 0
}
})
}
}}}
I am doing this in swift 3 using alamofire lirbary, this same call works elsewhere perfectly. 我正在使用alamofire库在swift 3中执行此操作,此调用在其他地方也可以正常使用。 However on here, i keep getting Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLKey= 但是在这里,我一直在获取Domain = NSURLErrorDomain代码= -999“已取消” UserInfo = {NSErrorFailingURLKey =
Why does my url call keeps getting cancelled for no reason?the same call works in elsewhere perfectly. 为什么我的url呼叫无缘无故地被取消?同一呼叫在其他地方也可以正常使用。
Your not saying anything about App Transport Security Settings, so I give it a try: 您没有说有关应用程序传输安全设置的任何内容,因此,我尝试一下:
What might happening is that App Transport Security is blocking your requests. 可能发生的情况是App Transport Security阻止了您的请求。
App Transport Security (ATS), introduced in iOS 9 and OS X v10.11, improves user security and privacy by requiring apps to use secure network connections over HTTPS. iOS 9和OS X v10.11中引入的应用程序传输安全性(ATS)通过要求应用程序使用基于HTTPS的安全网络连接来提高用户安全性和隐私性。
Your communication through higher-level APIs needs to be encrypted using TLS version 1.2 with forward secrecy. 您需要使用具有向前保密性的TLS 1.2版对通过高级API的通信进行加密。 If you try to make a connection that doesn't follow this requirement, an error is thrown. 如果尝试建立不符合此要求的连接,则会引发错误。 If your app needs to make a request to an insecure domain, you have to specify this domain in your app's Info.plist file. 如果您的应用需要向不安全的域发出请求,则必须在应用的Info.plist文件中指定此域。
To make an exception in info.plist file is easy. 在info.plist文件中设置异常很容易。 Add a NSAppTransportSecurity
key and add a dictionary of NSExceptionDomains
under. 添加NSAppTransportSecurity
项,并添加的字典NSExceptionDomains
下。 Then add your domains as keys and you don't need to write anything in the string value. 然后将您的域添加为键,您无需在字符串值中写入任何内容。 Also add a NSAllowsArbitraryLoads
key to allow insecure connections 还添加一个NSAllowsArbitraryLoads
键以允许不安全的连接
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>unsecuredomain.com</key>
<string></string>
<key>sub.unsecure.co.uk</key>
<string></string>
</dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.