7
多個圖像我想用一個單一的uploadTaskWithRequest
方法上載在背景的多個圖像。在嘗試下面的代碼返回NSData的從上傳任務在後臺會話不支持......請如何實現這一點背景上傳使用單NSURLSession uploadTaskWithRequest
func createRequest (param : NSDictionary ,imagearray :NSMutableArray, strURL : String) -> NSURLRequest {
let boundary = generateBoundaryString()
let url = NSURL(string: strURL)
let request = NSMutableURLRequest(URL: url!)
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = createBodyWithParameters(param, image_array:imagearray,boundary: boundary);
return request
}
func createBodyWithParameters(parameters: NSDictionary,image_array:NSMutableArray,boundary: String) -> NSData {
let body = NSMutableData()
for (key, value) in parameters {
if(value is String || value is NSString){
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString("\(value)\r\n")
}
}
var i = 0;
for image in image_array {
let filename = "image\(i).jpg"
let data = UIImagePNGRepresentation(image as! UIImage);
let mimetype = "image/png"
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(self.filePathKey)\"; filename=\"\(filename)\"\r\n")
body.appendString("Content-Type: \(mimetype)\r\n\r\n")
body.appendData(data!)
body.appendString("\r\n")
i += 1;
}
body.appendString("--\(boundary)--\r\n")
// NSLog("data %@",NSString(data: body, encoding: NSUTF8StringEncoding)!);
return body
}
func postrequestwithformdata(requesturl:String,postparams:NSDictionary,postformadata:NSMutableArray,requestId:Int)
{
self.requestid = requestId;
let requestformdata = self.createRequest(postparams, imagearray: postformadata, strURL: requesturl);
let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(Contants.identifier)
let session: NSURLSession = NSURLSession(configuration:configuration, delegate: self, delegateQueue: NSOperationQueue.mainQueue());
let task: NSURLSessionUploadTask = session.uploadTaskWithRequest(requestformdata, fromData: requestformdata.HTTPBody!);
task.resume();
}
但我有很多圖像形式的數據,如何處理這個? –
請更新您的問題,以澄清您正在嘗試做什麼。就目前而言,你的問題沒有提到任何有關多個圖像的問題。 –
查看[本教程](http://www.kaleidosblog.com/how-to-upload-images-using-swift-2-send-multipart-post-request),其中顯示瞭如何使用MIME編碼將多個圖像編碼成單個上傳請求。 –