@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
}
})
}
}}}
我使用alamofire lirbary在swift 3中这样做,同样的调用在其他地方工作得非常完美。但是在这里,我一直得到Domain = NSURLErrorDomain Code = -999“cancelled”UserInfo = {NSErrorFailingURLKey =
为什么我的网址会无缘无故地被取消?相同的通话在其他地方完美无缺。
答案 0 :(得分:0)
您对App Transport Security设置没有说什么,所以我试一试:
可能发生的事情是App Transport Security阻止了您的请求。
iOS 9和OS X v10.11中引入的App Transport Security(ATS)通过要求应用程序通过HTTPS使用安全网络连接来提高用户安全性和隐私性。
您通过更高级别的API进行的通信需要使用TLS 1.2版进行加密,并具有前向保密性。如果尝试建立不符合此要求的连接,则会引发错误。如果您的应用需要向不安全的域发出请求,则必须在应用的Info.plist文件中指定此域。
在info.plist文件中生成异常很容易。
添加NSAppTransportSecurity
密钥并在其下添加NSExceptionDomains
字典。然后将您的域添加为键,您不需要在字符串值中写入任何内容。还要添加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>