Commit ef5ceb8e authored by David黄金龙's avatar David黄金龙

Merge commit 'e947a8a1' into davidhuang

* commit 'e947a8a1':
  OOS接入和封装

# Conflicts:
#	galaxy/Podfile
parents be3aaf10 e947a8a1
...@@ -63,10 +63,10 @@ target 'galaxy' do ...@@ -63,10 +63,10 @@ target 'galaxy' do
pod 'SensorsAnalyticsSDK','4.6.0' pod 'SensorsAnalyticsSDK','4.6.0'
#主流APP分类切换滚动视图 #主流APP分类切换滚动视图
pod 'JXSegmentedView','1.3.0' pod 'JXSegmentedView','1.3.0'
#UI调试组件 #UI调试组件
# pod 'LookinServer',:configurations => ['Debug'],'1.2.6'
pod 'LookinServer','1.2.6',:subspecs => ['Swift'], :configurations => ['Debug'] pod 'LookinServer','1.2.6',:subspecs => ['Swift'], :configurations => ['Debug']
#阿里云OOS
pod 'AliyunOSSiOS','2.10.18'
end end
......
...@@ -13,6 +13,10 @@ ...@@ -13,6 +13,10 @@
0468D4262B495A5400CFB916 /* YHPickPhoneAddressViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D4252B495A5400CFB916 /* YHPickPhoneAddressViewController.swift */; }; 0468D4262B495A5400CFB916 /* YHPickPhoneAddressViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D4252B495A5400CFB916 /* YHPickPhoneAddressViewController.swift */; };
0468D4282B50D4AF00CFB916 /* YHPrivacyAlertView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D4272B50D4AF00CFB916 /* YHPrivacyAlertView.swift */; }; 0468D4282B50D4AF00CFB916 /* YHPrivacyAlertView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D4272B50D4AF00CFB916 /* YHPrivacyAlertView.swift */; };
0468D42B2B55019900CFB916 /* YHAnalytics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D42A2B55019900CFB916 /* YHAnalytics.swift */; }; 0468D42B2B55019900CFB916 /* YHAnalytics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D42A2B55019900CFB916 /* YHAnalytics.swift */; };
0468D42E2B5654A500CFB916 /* CoreTelephony.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0468D42D2B5654A500CFB916 /* CoreTelephony.framework */; };
0468D4302B5654B500CFB916 /* SystemConfiguration.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0468D42F2B5654B500CFB916 /* SystemConfiguration.framework */; };
0468D4312B5654C100CFB916 /* libresolv.tbd in Frameworks */ = {isa = PBXBuildFile; fileRef = 0468D42C2B56549200CFB916 /* libresolv.tbd */; };
0468D4342B56587B00CFB916 /* YHOOSManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0468D4332B56587B00CFB916 /* YHOOSManager.swift */; };
04808C062B4686510056D53C /* ATAuthSDK.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 04808C042B4686510056D53C /* ATAuthSDK.bundle */; }; 04808C062B4686510056D53C /* ATAuthSDK.bundle in Resources */ = {isa = PBXBuildFile; fileRef = 04808C042B4686510056D53C /* ATAuthSDK.bundle */; };
04808C082B4686C10056D53C /* ATAuthSDK_D.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 04808C032B4686510056D53C /* ATAuthSDK_D.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 04808C082B4686C10056D53C /* ATAuthSDK_D.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 04808C032B4686510056D53C /* ATAuthSDK_D.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
049A48A82B49417300D0C641 /* YHAboutUsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 049A48A72B49417300D0C641 /* YHAboutUsViewController.swift */; }; 049A48A82B49417300D0C641 /* YHAboutUsViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 049A48A72B49417300D0C641 /* YHAboutUsViewController.swift */; };
...@@ -128,6 +132,10 @@ ...@@ -128,6 +132,10 @@
0468D4252B495A5400CFB916 /* YHPickPhoneAddressViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHPickPhoneAddressViewController.swift; sourceTree = "<group>"; }; 0468D4252B495A5400CFB916 /* YHPickPhoneAddressViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHPickPhoneAddressViewController.swift; sourceTree = "<group>"; };
0468D4272B50D4AF00CFB916 /* YHPrivacyAlertView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHPrivacyAlertView.swift; sourceTree = "<group>"; }; 0468D4272B50D4AF00CFB916 /* YHPrivacyAlertView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHPrivacyAlertView.swift; sourceTree = "<group>"; };
0468D42A2B55019900CFB916 /* YHAnalytics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHAnalytics.swift; sourceTree = "<group>"; }; 0468D42A2B55019900CFB916 /* YHAnalytics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHAnalytics.swift; sourceTree = "<group>"; };
0468D42C2B56549200CFB916 /* libresolv.tbd */ = {isa = PBXFileReference; lastKnownFileType = "sourcecode.text-based-dylib-definition"; name = libresolv.tbd; path = usr/lib/libresolv.tbd; sourceTree = SDKROOT; };
0468D42D2B5654A500CFB916 /* CoreTelephony.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreTelephony.framework; path = System/Library/Frameworks/CoreTelephony.framework; sourceTree = SDKROOT; };
0468D42F2B5654B500CFB916 /* SystemConfiguration.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SystemConfiguration.framework; path = System/Library/Frameworks/SystemConfiguration.framework; sourceTree = SDKROOT; };
0468D4332B56587B00CFB916 /* YHOOSManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHOOSManager.swift; sourceTree = "<group>"; };
04808C032B4686510056D53C /* ATAuthSDK_D.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = ATAuthSDK_D.framework; sourceTree = "<group>"; }; 04808C032B4686510056D53C /* ATAuthSDK_D.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = ATAuthSDK_D.framework; sourceTree = "<group>"; };
04808C042B4686510056D53C /* ATAuthSDK.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = ATAuthSDK.bundle; sourceTree = "<group>"; }; 04808C042B4686510056D53C /* ATAuthSDK.bundle */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.plug-in"; path = ATAuthSDK.bundle; sourceTree = "<group>"; };
049A48A72B49417300D0C641 /* YHAboutUsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHAboutUsViewController.swift; sourceTree = "<group>"; }; 049A48A72B49417300D0C641 /* YHAboutUsViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = YHAboutUsViewController.swift; sourceTree = "<group>"; };
...@@ -217,6 +225,9 @@ ...@@ -217,6 +225,9 @@
buildActionMask = 2147483647; buildActionMask = 2147483647;
files = ( files = (
6203A87EDC96313BBE789D9C /* Pods_galaxy.framework in Frameworks */, 6203A87EDC96313BBE789D9C /* Pods_galaxy.framework in Frameworks */,
0468D42E2B5654A500CFB916 /* CoreTelephony.framework in Frameworks */,
0468D4312B5654C100CFB916 /* libresolv.tbd in Frameworks */,
0468D4302B5654B500CFB916 /* SystemConfiguration.framework in Frameworks */,
A57F1F252B48F09200B644E6 /* ATAuthSDK_D.framework in Frameworks */, A57F1F252B48F09200B644E6 /* ATAuthSDK_D.framework in Frameworks */,
); );
runOnlyForDeploymentPostprocessing = 0; runOnlyForDeploymentPostprocessing = 0;
...@@ -246,6 +257,14 @@ ...@@ -246,6 +257,14 @@
path = Analytics; path = Analytics;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
0468D4322B56581000CFB916 /* YHOOS */ = {
isa = PBXGroup;
children = (
0468D4332B56587B00CFB916 /* YHOOSManager.swift */,
);
path = YHOOS;
sourceTree = "<group>";
};
04808C022B4686510056D53C /* Frameworks */ = { 04808C022B4686510056D53C /* Frameworks */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
...@@ -275,6 +294,9 @@ ...@@ -275,6 +294,9 @@
8D4DE9CA401A76BB1ECBE46E /* Frameworks */ = { 8D4DE9CA401A76BB1ECBE46E /* Frameworks */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
0468D42F2B5654B500CFB916 /* SystemConfiguration.framework */,
0468D42D2B5654A500CFB916 /* CoreTelephony.framework */,
0468D42C2B56549200CFB916 /* libresolv.tbd */,
987C69D43AE8D85DC1930DCF /* Pods_galaxy.framework */, 987C69D43AE8D85DC1930DCF /* Pods_galaxy.framework */,
); );
name = Frameworks; name = Frameworks;
...@@ -429,6 +451,7 @@ ...@@ -429,6 +451,7 @@
A5ACE8EE2B4564F7002C94D2 /* Tools */ = { A5ACE8EE2B4564F7002C94D2 /* Tools */ = {
isa = PBXGroup; isa = PBXGroup;
children = ( children = (
0468D4322B56581000CFB916 /* YHOOS */,
0468D4292B55017400CFB916 /* Analytics */, 0468D4292B55017400CFB916 /* Analytics */,
04AF58BA2B4FB71C0066011A /* Localized */, 04AF58BA2B4FB71C0066011A /* Localized */,
A5ACE8F12B4564F7002C94D2 /* NetWork */, A5ACE8F12B4564F7002C94D2 /* NetWork */,
...@@ -838,6 +861,7 @@ ...@@ -838,6 +861,7 @@
A5ACE94A2B4564F7002C94D2 /* BsHUDProgressView.swift in Sources */, A5ACE94A2B4564F7002C94D2 /* BsHUDProgressView.swift in Sources */,
A5ACE9442B4564F7002C94D2 /* Array+Extension.swift in Sources */, A5ACE9442B4564F7002C94D2 /* Array+Extension.swift in Sources */,
0468D4282B50D4AF00CFB916 /* YHPrivacyAlertView.swift in Sources */, 0468D4282B50D4AF00CFB916 /* YHPrivacyAlertView.swift in Sources */,
0468D4342B56587B00CFB916 /* YHOOSManager.swift in Sources */,
A5ACE9522B4564F7002C94D2 /* YHIntelligentServiceViewController.swift in Sources */, A5ACE9522B4564F7002C94D2 /* YHIntelligentServiceViewController.swift in Sources */,
A5C5B2FD2B55361700A7C5D1 /* YHBannerModel.swift in Sources */, A5C5B2FD2B55361700A7C5D1 /* YHBannerModel.swift in Sources */,
A5ACE9462B4564F7002C94D2 /* BsHUDSquareBaseView.swift in Sources */, A5ACE9462B4564F7002C94D2 /* BsHUDSquareBaseView.swift in Sources */,
......
//
// YHOOSManager.swift
// galaxy
//
// Created by EDY on 2024/1/16.
// Copyright © 2024 https://www.galaxy-immi.com. All rights reserved.
//
import UIKit
public protocol Error {
var _domain: String { get }
var _code: Int { get }
var _userInfo: AnyObject? { get }
}
extension NSError : Error {
@nonobjc
public var _domain: String { return domain }
@nonobjc
public var _code: Int { return code }
@nonobjc
public var _userInfo: AnyObject? { return userInfo as NSDictionary }
}
class YHOOSDefine {
static let OSS_ACCESSKEY_ID: String = "access_key_id"
static let OSS_SECRETKEY_ID: String = "access_key_secret"
static let OSS_BUCKET_PUBLIC: String = "public-bucket"
static let OSS_BUCKET_PRIVATE: String = "private-bucket"
static let OSS_ENDPOINT: String = "http://oss-cn-region.aliyuncs.com"
static let OSS_MULTIPART_UPLOADKEY: String = "multipart"
static let OSS_RESUMABLE_UPLOADKEY: String = "resumable"
static let OSS_CALLBACK_URL: String = "http://oss-demo.aliyuncs.com:23450"
static let OSS_CNAME_URL: String = "http://www.cnametest.com/"
static let OSS_STSTOKEN_URL: String = "http://*.*.*.*.****/sts/getsts"
static let OSS_IMAGE_KEY: String = "testImage.png"
static let OSS_CRC64_ENABLE: Bool = true
static let OSS_CONTENT_TYPE: String = "Content-Type"
static let OSS_CONTENT_LENGTH: String = "Content-Length"
static let OSS_TEST_CONTENT_TYPE: String = "application/special"
static let OSS_APPEND_OBJECT_KEY: String = "appendObject"
static let SCHEME = "https://"
static let ENDPOINT = "oss-cn-hangzhou.aliyuncs.com"
static let CNAME_ENDPOINT = "oss.custom.com"
static let IP_ENDPOINT = "192.168.1.1:8080"
static let BUCKET_NAME = "BucketName"
static let OBJECT_KEY = "ObjectKey"
}
class YHOOSManager: NSObject, URLSessionDelegate {
static let share = YHOOSManager()
var mProvider: OSSAuthCredentialProvider!
var mClient: OSSClient!
override init() {
mProvider = OSSAuthCredentialProvider(authServerUrl: YHOOSDefine.OSS_STSTOKEN_URL)
mClient = OSSClient(endpoint: YHOOSDefine.OSS_ENDPOINT, credentialProvider: mProvider)
}
func getObject() {
let getObjectReq: OSSGetObjectRequest = OSSGetObjectRequest()
getObjectReq.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
getObjectReq.objectKey = YHOOSDefine.OSS_IMAGE_KEY
getObjectReq.downloadProgress = { (bytesWritten: Int64,totalBytesWritten : Int64, totalBytesExpectedToWrite: Int64) -> Void in
printLog("bytesWritten:\(bytesWritten),totalBytesWritten:\(totalBytesWritten),totalBytesExpectedToWrite:\(totalBytesExpectedToWrite)")
};
let task: OSSTask = mClient.getObject(getObjectReq);
task.continue({(t) -> OSSTask<AnyObject>? in
self.showResult(task: t)
return nil
})
task.waitUntilFinished()
printLog("Error:\(String(describing: task.error))")
}
func getImage() {
let getObjectReq: OSSGetObjectRequest = OSSGetObjectRequest()
getObjectReq.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
getObjectReq.objectKey = "ImageKey"
getObjectReq.xOssProcess = "image/resize,m_lfit,w_100,h_100"
getObjectReq.downloadProgress = { (bytesWritten: Int64,totalBytesWritten : Int64, totalBytesExpectedToWrite: Int64) -> Void in
printLog("bytesWritten:\(bytesWritten),totalBytesWritten:\(totalBytesWritten),totalBytesExpectedToWrite:\(totalBytesExpectedToWrite)")
};
let task: OSSTask = mClient.getObject(getObjectReq);
task.continue({(t) -> OSSTask<AnyObject>? in
self.showResult(task: t)
return nil
})
task.waitUntilFinished()
printLog("Error:\(String(describing: task.error))")
}
func getStsToken() {
let tcs = OSSTaskCompletionSource<AnyObject>()
let federationProvider: OSSFederationCredentialProvider = OSSFederationCredentialProvider(federationTokenGetter: {() ->OSSFederationToken? in
let url: URL = URL(string: YHOOSDefine.OSS_STSTOKEN_URL)!
let config: URLSessionConfiguration = URLSessionConfiguration.default
let session: URLSession = URLSession(configuration: config, delegate: self as URLSessionDelegate, delegateQueue: nil)
let task = session.dataTask(with: url, completionHandler: { (data, response, error) -> Void in
//Convert Data to Jsons
tcs.setResult(data as AnyObject)
})
task.resume()
tcs.task.waitUntilFinished()
let json = try? JSONSerialization.jsonObject(with: tcs.task.result as! Data,
options:.allowFragments) as? [String: Any]
print("Json Object:", json as Any)
//verify json
let accessKeyId = json?["AccessKeyId"]
let accessKeySecret = json?["AccessKeySecret"]
self.ossAlert(title: "notice", message: json?.description)
let token = OSSFederationToken()
token.tAccessKey = accessKeyId as! String
token.tSecretKey = accessKeySecret as! String
return token
})
do {
try federationProvider.getToken()
} catch{
print("get Error")
}
}
func headObject() {
let objectKey = "key"
if objectKey.isEmpty {
ossAlert(title: nil, message: "objectKey can not be empty!")
}
let request = OSSHeadObjectRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectKey = objectKey
let task: OSSTask = mClient.headObject(request)
task.continue({(task) -> OSSTask<AnyObject>? in
self.showResult(task: task)
return nil
})
task.waitUntilFinished()
}
func getBucket() {
let request = OSSGetBucketRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
let task = mClient.getBucket(request)
task.continue( { (t) -> Any? in
if let result = t.result as? OSSGetBucketResult {
self.showResult(task: OSSTask(result: result.contents as AnyObject))
} else {
self.showResult(task: t)
}
return nil
})
}
func getBucketACL() -> Void {
let request = OSSGetBucketACLRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
let task = mClient.getBucketACL(request)
task.continue( { (t) -> Any? in
if let result = t.result as? OSSGetBucketACLResult {
self.showResult(task: OSSTask(result: result.aclGranted as AnyObject))
} else {
self.showResult(task: t)
}
return nil
})
}
func createBucket() -> Void {
let request = OSSCreateBucketRequest()
request.bucketName = "com-dhc-test"
let task = mClient.createBucket(request)
task.continue( { (t) -> Any? in
self.showResult(task: t)
return nil
})
}
func deleteBucket() -> Void {
let request = OSSDeleteBucketRequest()
request.bucketName = "com-dhc-test"
let task = mClient.deleteBucket(request)
task.continue( { (t) -> Any? in
self.showResult(task: t)
return nil
})
}
func putObject(image: UIImage) {
let request = OSSPutObjectRequest()
request.uploadingData = image.pngData()!
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectKey = "landscape-painting.jpeg"
request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
printLog("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
};
let provider = OSSFederationTokenCredentialProvider {
let tcs = TaskCompletionSource()
DispatchQueue(label: "test").async {
Thread.sleep(forTimeInterval: 10)
let token = OSSFederationToken()
token.tAccessKey = "STS.tAccessKey"
token.tSecretKey = "tSecretKey"
token.tToken = "tToken"
token.expirationTimeInGMTFormat = "2023-05-23T07:34:27Z"
// or tcs.trySetError(<#T##error: Error##Error#>)
tcs.trySetResult(token)
}
tcs.wait(timeout: 5)
if let error = tcs.task.error {
let nsError = error as NSError
if nsError.code == OSSClientErrorCODE.codeNotKnown.rawValue,
let errorMessage = nsError.userInfo[OSSErrorMessageTOKEN] as? String,
errorMessage == "TaskCompletionSource wait timeout." {
// 超时错误
}
throw error
} else if let result = tcs.task.result as? OSSFederationToken {
return result
}
throw NSError(domain: OSSClientErrorDomain,
code: OSSClientErrorCODE.codeSignFailed.rawValue,
userInfo: [OSSErrorMessageTOKEN : "Can not get FederationToken."])
}
let client = OSSClient(endpoint: YHOOSDefine.OSS_ENDPOINT, credentialProvider: provider)
let task = client.putObject(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
}).waitUntilFinished()
}
func multipartUpload() {
let request = OSSMultipartUploadRequest()
request.uploadingFileURL = Bundle.main.url(forResource: "wangwang", withExtension: "zip")!
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectKey = "wangwang(swift).zip"
request.partSize = 102400;
request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
printLog("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
};
let provider = OSSAuthCredentialProvider(authServerUrl: YHOOSDefine.OSS_STSTOKEN_URL)
let client = OSSClient(endpoint: YHOOSDefine.OSS_ENDPOINT, credentialProvider: provider)
let task = client.multipartUpload(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
}).waitUntilFinished()
}
func sequentialMultipartUpload() {
let request = OSSResumableUploadRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE;
request.objectKey = "sequential-swift-multipart"
request.uploadingFileURL = Bundle.main.url(forResource: "wangwang", withExtension: "zip")!
request.deleteUploadIdOnCancelling = false
request.crcFlag = OSSRequestCRCFlag.open
let filePath = Bundle.main.path(forResource: "wangwang", ofType: "zip")
request.contentSHA1 = OSSUtil.sha1(withFilePath: filePath)
let task = mClient.sequentialMultipartUpload(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
return nil
}).waitUntilFinished()
}
func resumableUpload() {
var request = OSSResumableUploadRequest()
request.uploadingFileURL = Bundle.main.url(forResource: "wangwang", withExtension: "zip")!
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.deleteUploadIdOnCancelling = false
request.objectKey = "wangwang(swift).zip"
let cacheDir = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).first
request.recordDirectoryPath = cacheDir!
request.partSize = 102400
request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
printLog("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
if totalBytesSent > (totalBytesExpectedToSend / 2) {
request.cancel()
}
}
var task = mClient.resumableUpload(request)
task.continue({ (t) -> Any? in
print("Error: \(String(describing: t.error))")
return nil
}).waitUntilFinished()
request = OSSResumableUploadRequest()
request.uploadingFileURL = Bundle.main.url(forResource: "wangwang", withExtension: "zip")!
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectKey = "wangwang(swift).zip"
request.partSize = 102400;
request.deleteUploadIdOnCancelling = false
request.recordDirectoryPath = cacheDir!
request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
printLog("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)")
}
task = mClient.resumableUpload(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
return nil
}).waitUntilFinished()
}
func putObjectWithXML() {
let request = OSSPutObjectRequest()
request.uploadingFileURL = Bundle.main.url(forResource: "test", withExtension: "xml")!
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectKey = "test.xml"
request.contentSHA1 = OSSUtil.sha1(withFilePath: Bundle.main.path(forResource: "test", ofType: "xml"))
request.uploadProgress = { (bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) -> Void in
print("bytesSent:\(bytesSent),totalBytesSent:\(totalBytesSent),totalBytesExpectedToSend:\(totalBytesExpectedToSend)");
};
let task = mClient.putObject(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
}).waitUntilFinished()
}
func getObjectACL() {
let request = OSSGetObjectACLRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectName = YHOOSDefine.OSS_IMAGE_KEY
let task = mClient.getObjectACL(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
return nil
}).waitUntilFinished()
}
func deleteMultipleObjects() {
let request = OSSDeleteMultipleObjectsRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.keys = ["testFor5m"]
request.quiet = false
request.encodingType = "url"
let task = mClient.deleteMultipleObjects(request)
task.continue({ (t) -> Any? in
self.showResult(task: t)
return nil
}).waitUntilFinished()
}
func triggerCallBack() {
let provider = OSSPlainTextAKSKPairCredentialProvider.init(plainTextAccessKey: "AK", secretKey: "SK")
let pClient = OSSClient.init(endpoint: YHOOSDefine.OSS_ENDPOINT, credentialProvider: provider)
let request = OSSCallBackRequest()
request.bucketName = YHOOSDefine.OSS_BUCKET_PRIVATE
request.objectName = "file1m"
request.callbackVar = ["key1": "value1",
"key2": "value2"]
request.callbackParam = ["callbackUrl": YHOOSDefine.OSS_CALLBACK_URL,
"callbackBody": "test"]
let task = pClient.triggerCallBack(request)
task.continue({ (t) -> Any? in
if (t.result != nil) {
let result = t.result as! OSSCallBackResult;
self .ossAlert(title: "提示", message: result.serverReturnJsonString);
}
return nil
}).waitUntilFinished()
}
//验证结果
func showResult(task: OSSTask<AnyObject>?) {
if (task?.error != nil) {
let error: NSError = (task?.error)! as NSError
self.ossAlert(title: "error", message: error.description)
} else {
let result = task?.result
self.ossAlert(title: "notice", message: result?.description)
}
}
func ossAlert(title: String?,message:String?) {
DispatchQueue.main.async {
let alertCtrl = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alertCtrl.addAction(UIAlertAction(title: "confirm", style: UIAlertAction.Style.default, handler: { (action) in
print("\(action.title!) has been clicked");
alertCtrl.dismiss(animated: true, completion: nil)
}))
UIViewController.current?.present(alertCtrl, animated: true, completion: nil)
}
}
}
public class OSSFederationTokenCredentialProvider: OSSFederationCredentialProvider {
var token: OSSFederationToken?
private var tokenGetter: () throws -> OSSFederationToken
public init(tokenGetter: @escaping () throws -> OSSFederationToken) {
self.tokenGetter = tokenGetter
super.init()
}
public override func getToken() throws -> OSSFederationToken {
do {
if var token = token {
if let expirationTimeInGMTFormat = token.expirationTimeInGMTFormat {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = TimeZone(identifier: "GMT")
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let data = dateFormatter.date(from: expirationTimeInGMTFormat) {
token.expirationTimeInMilliSecond = Int64(data.timeIntervalSince1970 * 1000)
}
}
let expirationDate = Date(timeIntervalSince1970: TimeInterval(token.expirationTimeInMilliSecond / 1000))
let interval = expirationDate.timeIntervalSince(NSDate.oss_clockSkewFixed())
if interval < 5 * 60 {
token = try self.tokenGetter()
self.token = token
}
return token
} else {
let token = try self.tokenGetter()
self.token = token
return token
}
} catch {
throw NSError(domain: OSSClientErrorDomain,
code: OSSClientErrorCODE.codeSignFailed.rawValue,
userInfo: [OSSErrorMessageTOKEN : error])
}
}
}
public class TaskCompletionSource: OSSTaskCompletionSource<AnyObject> {
public func wait(timeout: TimeInterval) {
let timer = DispatchSource.makeTimerSource()
timer.schedule(deadline: .now() + timeout)
timer.setEventHandler {
if !self.task.isCompleted {
let error = NSError(domain: OSSClientErrorDomain,
code: OSSClientErrorCODE.codeNotKnown.rawValue,
userInfo: [OSSErrorMessageTOKEN : "TaskCompletionSource wait timeout."])
self.trySetError(error)
}
}
timer.resume()
task.waitUntilFinished()
timer.cancel()
}
}
...@@ -10,5 +10,6 @@ ...@@ -10,5 +10,6 @@
#import <Bugly/Bugly.h> #import <Bugly/Bugly.h>
#import <ATAuthSDK_D/ATAuthSDK.h> #import <ATAuthSDK_D/ATAuthSDK.h>
#import <AliyunOSSiOS/OSSService.h>
#endif /* galaxy_Bridge_Header_h */ #endif /* galaxy_Bridge_Header_h */
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment