gpt4 book ai didi

ios - Swift 4 - 使用 URLSession 获取上传图片进度

转载 作者:行者123 更新时间:2023-11-28 13:59:46 26 4
gpt4 key购买 nike

我下面有这种代码

func upload(){
let img = UIImage(named: "1")
let imgData = UIImageJPEGRepresentation(img!, 1)
let data = imgData?.base64EncodedString()

var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("\(auth)", forHTTPHeaderField: "Authorization")
request.setValue("application/xml", forHTTPHeaderField: "Content-Type")

var postString = "<uploadrequest>"
postString += "<folderid>123</folderid>"
postString += "<folder_name>images</folder_name>"
postString += "<image_byte>\(data!)</image_byte>"
postString += "</uploadrequest>"

request.httpBody = postString.data(using: .utf8)

let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)

let task = session.uploadTask(with: request, from: imgData!, completionHandler: {
(data, response, error) -> Void in

if let error = error {
print(error)
return
}
if let data = data {
_ = self.parseJsonData(data: data)
}
})

task.resume()
}

func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
print("sent:", totalBytesSent, "from:", totalBytesExpectedToSend)

let size = totalBytesSent / totalBytesExpectedToSend
self.progressbar.progress = Float(size)
}

我的目标是使用 API 上传图片并获取其上传进度。图像被转换为​​ base64 并插入到 <image_byte>\(data!)</image_byte>。在 API 的 poststring 上。

然后我得到的是这样的:

sent: 32768 from: 927220 sent: 65536 from: 927220 sent: 131072 from: 927220 sent: 163840 from: 927220 sent: 262144 from: 927220 sent: 294912 from: 927220 sent: 360448 from: 927220 sent: 393216 from: 927220 sent: 425984 from: 927220 sent: 491520 from: 927220 sent: 524288 from: 927220 sent: 557056 from: 927220 sent: 589824 from: 927220 sent: 622592 from: 927220 sent: 655360 from: 927220 sent: 688128 from: 927220 sent: 720896 from: 927220 sent: 786432 from: 927220 sent: 819200 from: 927220 sent: 851968 from: 927220 sent: 927220 from: 927220 Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

但是如果我使用其他类似的方法(没有 uploadTask),效果很好但没有上传进度。

let task = URLSession.shared.dataTask(with: request, completionHandler: {
(data, response, error) -> Void in

if let error = error {
print(error)
return
}
if let data = data {
_ = self.parseJsonData(data: data)
}
})

我试过了 Alamofire也。 Alamofirerequest功能成功但仍然没有上传进度和Alamofireupload函数 (multipartformData) 出现此错误:

responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.jsonSerializationFailed(error: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 3." UserInfo={NSDebugDescription=Invalid value around character 3.}))

我想知道我的代码是否有误。你能告诉我应该如何处理我的代码吗?或者问题出在我的 API 上,因为我的 API 只接受 base64代码?

如果你想看我的Alamofire代码,它是 there

拜托,有人帮我解决这个问题。

谢谢! :)

编辑 1

这是我通过请求函数得到的结果(没有上传函数)

{
"media_preview" = {
"image_media" = {
fileid = 4928501;
filename = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
folderpath = "product\\66861/images800\\";
height = 533;
src = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
width = 800;
};
"medium_media" = {
fileid = 4928503;
filename = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
folderpath = "product\\66861/images500\\";
height = 333;
src = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
width = 500;
};
"small_media" = {
fileid = 4928503;
filename = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
folderpath = "\product\\66861/images300\\";
height = 200;
src = "/zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
width = 300;
};
"source_media" = {
fileid = 4928499;
filename = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
folderpath = "\\product\\66861images\\";
height = 666;
src = "/zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
width = 999;
};
"thumbnail_media" = {
fileid = 4928507;
filename = "zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
folderpath = \\product\\66861/thumb\\";
height = 150;
src = "/zhzvoHBb1ogda9bps13R5IavYiadCm.jpg";
width = 150;
};
};
responsestatus = {
"access_token" = "<null>";
code = 00;
description = Success;
};
}

编辑 2这是 parseJsonData(data: Data) 的代码

func parseJsonData(data: Data) {
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary
print(jsonResult!)
} catch {
print(error)
}
}

最佳答案

要获取进度,请使用以下 URLSession 的委托(delegate)方法,您可以在 didReceiveData 方法中获取进度

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {

//here you can get full lenth of your content
expectedContentLength = Int(response.expectedContentLength)
println(expectedContentLength)
completionHandler(NSURLSessionResponseDisposition.Allow)
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {


buffer.appendData(data)

let percentageDownloaded = Float(buffer.length) / Float(expectedContentLength)
progress.progress = percentageDownloaded
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
//use buffer here.Download is done
progress.progress = 1.0 // download 100% complete
}

关于ios - Swift 4 - 使用 URLSession 获取上传图片进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53650584/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com