Consume SOAP API - swift

I want to consume a SOAP API but I am facing problem.
My delegate methods are not called and URL variable shows unable to read data which is of NSURL type.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, XMLParserDelegate {
var mutableData:NSMutableData = NSMutableData.init()
var currentElementName:NSString = ""
#IBOutlet var txtCelsius : UITextField!
#IBOutlet var txtFahrenheit : UITextField!
override func viewDidLoad() {
super.viewDidLoad()
let celcius = "24"
let soapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='https://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='https://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CelsiusToFahrenheit xmlns='https://www.w3schools.com/xml/'><Celsius>\(String(describing: celcius))</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
let urlString = "https://www.w3schools.com/xml/tempconvert.asmx"
print(urlString)
if let url = NSURL(string: urlString)
{
print(url)
let theRequest = NSMutableURLRequest(url: url as URL)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
theRequest.httpMethod = "POST"
theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8, allowLossyConversion: false)
let connection = NSURLConnection(request: theRequest as URLRequest, delegate: self, startImmediately: true)
connection!.start()
}
}
private func connection(connection: NSURLConnection!, didReceiveResponse response: URLResponse!) {
mutableData.length = 0;
}
private func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
mutableData.append(data as Data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
let xmlParser = XMLParser(data: mutableData as Data)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
}
func parser(_ parser: XMLParser, foundCharacters string: String)
{
if currentElementName == "CelsiusToFahrenheit"
{
txtFahrenheit.text = string
}
}
}

Related

Swift XML Parser not firing properly

I'm reasonably new to Swift and I'm trying to read data from a web service. The data is returned and according to the parser it was parsed successfully. All I have at the moment is when the data is returned it's to be placed in a textview and it does do this successfully. But the returned XML is not being parsed. I have breakpoints in all 4 parser functions but none of them are being hit. It's as though they are not being fired. Here's my code (this is just playing at the moment so please be nice :) )
import UIKit
import Foundation
class ViewController: UIViewController, XMLParserDelegate{
var currentElementName:String = ""
var foundCharacters = ""
var parser = XMLParser()
var is_SoapMessage: String = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body></soap:Body></soap:Envelope>"
override func viewDidLoad() {
super.viewDidLoad()
parser.delegate = self
//clear all arrays
let Emp = EmployeeDetails()
Emp.ID.removeAll()
Emp.Name.removeAll()
Emp.Mobile.removeAll()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func GetServiceBtn(_ sender: Any) {
Test1()
}
//Text box to see what's returned
#IBOutlet weak var OutputTxt: UITextView!
//First test of using web services
func Test1(){
let URL: String = "http://192.168.1.106:8080/Service.asmx"
let WebRequ = NSMutableURLRequest(url: NSURL(string: URL)! as URL)
let session = URLSession.shared
WebRequ.httpMethod = "POST"
WebRequ.httpBody = is_SoapMessage.data(using: String.Encoding.utf8)
WebRequ.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
WebRequ.addValue(String(is_SoapMessage), forHTTPHeaderField: "Content-Length")
WebRequ.addValue("MyServices/GetEmployeesFullNames", forHTTPHeaderField: "SOAPAction")
var Str: String = ""
let task = session.dataTask(with: WebRequ as URLRequest, completionHandler: {data, response, error -> Void in
let strData = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
Str = String(strData!) as String
if Str != ""{
self.PopulateTxt(Detail: Str)
self.ReadEmployeeResults(Data: data!)
print(Str)
}
if error != nil
{
print("Error: " + error.debugDescription)
}
})
task.resume()
}
//Process returned data
func ReadEmployeeResults(Data: Data){
self.parser = XMLParser(data: Data)
let success:Bool = parser.parse()
if success {
print("parse success!")
let Emp = EmployeeDetails()
print("Employee Name count \(Emp.Name.count)")
print("Employee ID count \(Emp.ID.count)")
print("Employee Mobile count \(Emp.ID.count)")
print(Emp.Name[0])
} else {
print("parse failure!")
}
}
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
print("In Parser")
currentElementName = elementName
if(elementName=="Table")
{
let Emp = EmployeeDetails()
for string in attributeDict {
let strvalue = string.value as NSString
switch string.key {
case "Emp_ID":
Emp.ID.append(Int(strvalue as String)!)
break
case "Emp_FullName":
Emp.Name.append(strvalue as String)
break
case "Emp_Mobile":
Emp.Mobile.append(strvalue as String)
break
default:
break
}
}
}
}
func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
print("In didEndElement Parser")
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
if currentElementName == "Emp_ID" {
print(string)
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
print("failure error: ", parseError)
}
func PopulateTxt(Detail: String){
DispatchQueue.main.async {
self.OutputTxt.text = Detail //code that caused error goes here
}
}
}
class EmployeeDetails {
var Name = [String()]
var ID = [Int()]
var Mobile = [String()]
}
You are not setting the parser's delegate in your ReadEmployeeResults function. The XMLParser instance you create there is not the same one you create initially.
There is no need for your parser property or setting its delegate in viewDidLoad. Simply create the one you need in the function.
func ReadEmployeeResults(Data: Data){
let parser = XMLParser(data: Data)
parser.delegate = self
let success = parser.parse()
if success {
print("parse success!")
let Emp = EmployeeDetails()
print("Employee Name count \(Emp.Name.count)")
print("Employee ID count \(Emp.ID.count)")
print("Employee Mobile count \(Emp.ID.count)")
print(Emp.Name[0])
} else {
print("parse failure!")
}
}
Also note that variable and function names should start with lowercase letters.

how to get json array from xml response in swift

im new to ios. I'm making simple login app using soap request.
so the problem is when I get a response from the server it looks like
Optional(<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body>
<CreateLoginResponse xmlns="http://tempuri.org/">
<CreateLoginResult>[{"DelBoyId":36,"DelBoy_Fname":"abc-xyz","Password":"123","DelBoy_Email":"abc#gmail.com","DelBoy_Contact":"123","RoleName":"Admin"}]
</CreateLoginResult>
</CreateLoginResponse>
</soap:Body>
</soap:Envelope>).
and I want to store this key value [{"DelBoyId":36,"DelBoy_Fname":"abc-xyz","Password":"123","DelBoy_Email":"abc#gmail.com","DelBoy_Contact":"123","RoleName":"Admin"}] in session.
how can I do this ? please help me.
thank you.
here is my code
import UIKit
class LoginPageViewController: UIViewController, NSXMLParserDelegate {
#IBOutlet var txtUserEmail: UITextField!
#IBOutlet var txtUserPassword: UITextField!
var webData : NSMutableData?
var parser : NSXMLParser?
var flag : Bool?
var capturedString : String?
func processTerrorSaftyTips(data : NSData){
parser = NSXMLParser(data: data)
parser!.delegate = self
parser!.parse()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func loginButtonTapped(sender: AnyObject) {
let mobile = txtUserEmail.text;
let password = txtUserPassword.text;
let soapMessage = String(format: "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http:/www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CreateLogin xmlns='http://tempuri.org/'><mobile>"+mobile!+"</mobile><pasword>"+password!+"</pasword></CreateLogin></soap:Body></soap:Envelope>");
let url = NSURL(string: "http://23.91.115.57/nagifts/NaGiftsWebService.asmx");
let theRequest = NSMutableURLRequest (URL: url!);
let soapLength = String(soapMessage.characters.count)
theRequest.addValue("text/xml", forHTTPHeaderField: "Content-Type");
theRequest.addValue(soapLength, forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST";
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: false);
let urlConnection = NSURLConnection(request: theRequest , delegate: self);
}
func connection(connection: NSURLConnection, didFailWithError error: NSError){
}
func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse){
webData = NSMutableData()
}
func connection(connection: NSURLConnection, didReceiveData data: NSData){
webData!.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection){
processTerrorSaftyTips(webData!)
}
func parserDidStartDocument(parser: NSXMLParser){
flag = false
capturedString = ""
}
func parserDidEndDocument(parser: NSXMLParser){
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]){
flag = false
capturedString = ""
if elementName == "CreateLoginResult"
{
flag = true
}
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?){
flag = false
if elementName == "CreateLoginResult"
{
print((capturedString!))
}
}
func parser(parser: NSXMLParser, foundCharacters string: String){
if flag! {
capturedString = capturedString! + string
}
}
func parser(parser: NSXMLParser, parseErrorOccurred parseError: NSError){
}
}
Swift3:
Declare any array because your response is in array
var arrayFromResult = NSMutableArray()
Next go to Parse DidEndElement and add foundCharacters to Array do like this
if elementName == "CreateLoginResult"
{
print((capturedString!))
arrayFromResult.add(capturedString)
}
Usage Of array Or retrieve Dictionary Values from Array
for var i in 0..<arrayFromResult.count {
let dictFromArray = arrayFromResult.object(at: i) as! NSDictionary
let name = dictFromArray.value(forKey: "DelBoy_Fname") as! String
print(name)
let password = dictFromArray.value(forKey: "Password") as! String
print(password)
}

Upload video to server by using Alamofire

I used alamofire to upload the chosen image to the server and It's working but now I don't know how I can make the same thing for the selected video from device after select it and store the path of this video at variable , how I can use alamofire to upload this video to server ?
My code:
import UIKit
import Alamofire
import AVKit
import AVFoundation
import MediaPlayer
import MobileCoreServices
class sendFinalNews: UIViewController, UIImagePickerControllerDelegate,UINavigationControllerDelegate {
#IBOutlet weak var titleText: UITextField!
#IBOutlet weak var msgDetailText: UITextView!
#IBOutlet weak var sendIndicator: UIActivityIndicatorView!
#IBOutlet weak var loadedImage: UIImageView!
var CUSTOMER_KEY = "dkeqnq9fmkhq"
var titlemsg = ""
var detailmsg = ""
var videoURL:String!
var playerViewController = AVPlayerViewController()
var playerView = AVPlayer()
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func addVideoButton(sender: AnyObject) {
var videoPickerController = UIImagePickerController()
videoPickerController.delegate = self
videoPickerController.sourceType = .SavedPhotosAlbum
videoPickerController.mediaTypes = [kUTTypeMovie as String]
self.presentViewController(videoPickerController, animated: true, completion: nil)
}
#IBAction func addImageButton(sender: AnyObject) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
self.presentViewController(ImagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
let url = info[UIImagePickerControllerMediaURL]
print(url)
if mediaType.isEqualToString(kUTTypeImage as String)
{
loadedImage.image = info[UIImagePickerControllerOriginalImage] as? UIImage
}
else if mediaType.isEqualToString(kUTTypeMovie as String)
{
let urlOfVideo = info[UIImagePickerControllerMediaURL] as? NSURL
if let url = urlOfVideo {
print("video loadaed")
videoURL = String(urlOfVideo)
print(videoURL)
}
}
self.dismissViewControllerAnimated(true, completion: nil )
}
#IBAction func backButton(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil )
}
#IBAction func sendButton(sender: AnyObject) {
titlemsg = titleText.text!
detailmsg = msgDetailText.text!
self.sendIndicator.startAnimating()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
// ...
// heavy loop codes here
// ...
self.uploadFile()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.sendIndicator.stopAnimating()
})
});
}
func uploadFile() {
//let image = UIImage(named: "ios9.jpg")
let newimage : NSData = UIImageJPEGRepresentation(loadedImage.image!, 32)!
let newRandomName = randomStringWithLength(32)
let fname = (newRandomName as String) + ".jpg"
let parameters = [
"pic" :NetData(data: newimage, mimeType: .ImageJpeg, filename: fname),
"msg" :self.detailmsg,
"customer_key" : self.CUSTOMER_KEY
]
let urlRequest = self.urlRequestWithComponents("myURLhere", parameters: parameters)
Alamofire.upload(urlRequest.0, data: urlRequest.1)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
print("\(totalBytesWritten) / \(totalBytesExpectedToWrite)")
}
.responseJSON { response in
debugPrint(response)
}
}
func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {
// create url request to send
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
//let boundaryConstant = "myRandomBoundary12345"
let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())"
let contentType = "multipart/form-data;boundary="+boundaryConstant
mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
// create upload data to send
let uploadData = NSMutableData()
// add parameters
for (key, value) in parameters {
uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
if value is NetData {
// add image
let postData = value as! NetData
//uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
// append content disposition
let filenameClause = " filename=\"\(postData.filename)\""
let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n"
let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentDispositionData!)
// append content type
//uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) // mark this.
let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n"
let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding)
uploadData.appendData(contentTypeData!)
uploadData.appendData(postData.data)
}else{
uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!)
}
}
uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData)
}
func randomStringWithLength (len : Int) -> NSString {
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString : NSMutableString = NSMutableString(capacity: len)
for (var i=0; i < len; i++){
var length = UInt32 (letters.length)
var rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
return randomString
}
}
NetData class:
import Foundation
import UIKit
enum MimeType: String {
case ImageJpeg = "image/jpeg"
case ImagePng = "image/png"
case ImageGif = "image/gif"
case Json = "application/json"
case Unknown = ""
func getString() -> String? {
switch self {
case .ImagePng:
fallthrough
case .ImageJpeg:
fallthrough
case .ImageGif:
fallthrough
case .Json:
return self.rawValue
case .Unknown:
fallthrough
default:
return nil
}
}
}
class NetData
{
let data: NSData
let mimeType: MimeType
let filename: String
init(data: NSData, mimeType: MimeType, filename: String) {
self.data = data
self.mimeType = mimeType
self.filename = filename
}
init(pngImage: UIImage, filename: String) {
data = UIImagePNGRepresentation(pngImage)!
self.mimeType = MimeType.ImagePng
self.filename = filename
}
init(jpegImage: UIImage, compressionQuanlity: CGFloat, filename: String) {
data = UIImageJPEGRepresentation(jpegImage, compressionQuanlity)!
self.mimeType = MimeType.ImageJpeg
self.filename = filename
}
}

How do I call a SOAP web service in Swift 2?

I want to call web service for Swift 2. But it never works. This is my code.
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, NSURLConnectionDelegate, NSXMLParserDelegate {
var mutableData:NSMutableData = NSMutableData.init()
var currentElementName:NSString = ""
#IBOutlet var txtCelsius : UITextField!
#IBOutlet var txtFahrenheit : UITextField!
#IBAction func actionConvert(sender : AnyObject) {
let celcius = txtCelsius.text
let soapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CelsiusToFahrenheit xmlns='http://www.w3schools.com/xml/'><Celsius>\(celcius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
let urlString = "http://www.w3schools.com/xml/tempconvert.asmx"
let url = NSURL(string: urlString)
let theRequest = NSMutableURLRequest(URL: url!)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) // or false
let connection = NSURLConnection(request: theRequest, delegate: self, startImmediately: true)
connection!.start()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func connection(connection: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
mutableData.length = 0;
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
mutableData.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
let xmlParser = NSXMLParser(data: mutableData)
xmlParser.delegate = self
xmlParser.parse()
xmlParser.shouldResolveExternalEntities = true
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if currentElementName == "CelsiusToFahrenheit" {
txtFahrenheit.text = string
}
}
NSURLConnection is deprecated, use NSURLSession instead.
Here's an example of a function doing what you want with NSURLSession and a callback:
func getFarenheit(celsius celsius: Int, completion: (result: String) -> Void) {
let soapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><CelsiusToFahrenheit xmlns='http://www.w3schools.com/xml/'><Celsius>\(celsius)</Celsius></CelsiusToFahrenheit></soap:Body></soap:Envelope>"
let urlString = "http://www.w3schools.com/xml/tempconvert.asmx"
if let url = NSURL(string: urlString) {
let theRequest = NSMutableURLRequest(URL: url)
theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")
theRequest.addValue((soapMessage), forHTTPHeaderField: "Content-Length")
theRequest.HTTPMethod = "POST"
theRequest.HTTPBody = soapMessage.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
NSURLSession.sharedSession().dataTaskWithRequest(theRequest) { (data, response, error) in
if error == nil {
if let data = data, result = String(data: data, encoding: NSUTF8StringEncoding) {
completion(result: result)
}
} else {
print(error!.debugDescription)
}
}.resume()
}
}
Use it like this with a "trailing closure":
getFarenheit(celsius: 42) { (result) in
print(result)
}
It prints the data containing the XML and the converted value:
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><CelsiusToFahrenheitResponse xmlns="http://www.w3schools.com/xml/"><CelsiusToFahrenheitResult>107.6</CelsiusToFahrenheitResult></CelsiusToFahrenheitResponse></soap:Body></soap:Envelope>

Download Multiple File at a time in Swift

I was finally able to download 1 video from a server using the following code:
import UIKit
class ViewController: UIViewController, NSURLConnectionDelegate {
var file:NSFileHandle?
#IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
downloadVideo()
}
func downloadVideo(sender: UIButton) {
let urlPath: String = "http://www.ebookfrenzy.com/ios_book/movie/movie.mov"
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
var fileName = "test.mov"
var fileAtPath = fileInDocumentsDirectory(fileName)
if(NSFileManager.defaultManager().fileExistsAtPath(fileAtPath) == false)
{
NSFileManager.defaultManager().createFileAtPath(fileAtPath, contents: nil, attributes: nil)
}
file = NSFileHandle(forWritingAtPath: fileAtPath)!
if ((file) != nil){
file!.seekToEndOfFile()
}
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
//write,each,data,received
if(data != nil){
if((file) != nil){
file!.seekToEndOfFile()
}
file!.writeData(data)
}
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
file!.closeFile()
}
func documentsDirectory() -> String {
let documentsFolderPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as String
return documentsFolderPath
}
func fileInDocumentsDirectory(filename: String) -> String{
return documentsDirectory().stringByAppendingPathComponent(filename)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
But I need to download a lot of video files(I have at least 100 URL), how can I do it? I was thinking of doing it one at a time but I guess that in that approach I will have a lot of NSURLConnections instances and maybe I will eat all my RAM, Can you please help me to learn the right form of multiple files download?
Thank you so much!
You can use a concurrent queue to limit the max number of connections at a time.
func downloadVideo(sender: UIButton) {
for urlPath in urlPaths {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
var url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
}
}
}
If you want to customize the max number of connections, check here:
Can I limit concurrent requests using GCD?