Alamofire 4 Multipart Form Data Video Upload

By Francis Fuerte and Chris Ching


If y'all accept been diving deep into iOS evolution yous may have already see accessing data/databases using URLSession , this is fine and all only sometimes it gets annoying to use, this is where Alamofire comes in. And then what is Alamofire?

What is Alamofire?

Alamofire is an elegant and composable way to interface to HTTP network requests. Information technology builds on top of Apple's URL Loading Organization provided by the Foundation framework. At the core of the organization is URLSession and the URLSessionTask subclasses. Alamo burn down wraps these APIs, and many others, in an easier to use interface and provides a variety of functionality necessary for modern awarding development using HTTP networking.

Part ane: Installation

You demand to have cocoapods installed for this, one time that is ready, allow'due south create our xcode project. For this example we accept created an xcode project chosen AlamofireTest.

We need to install the Alamofire Cocoapod
We need to install the Alamofire Cocoapod

Nosotros'll exist using Cocoapods to install the Alamofire library. If need to set Cocoapods on your system first, bank check out my Cocoapods tutorial.

Now navigate to your project binder and open a concluding window, besides navigate the final window to the project location.

Navigate to your project directory and type pod init to create your podfile
Navigate to your project directory and type pod init to create your podfile

In one case there you lot should practise a "pod init" in your terminal

It will then output a file named Podfile .

Add the Alamofire pod to your podfile
Add together the Alamofire pod to your podfile

Open the Podfile in Textedit and add together the line pod "Alamofire", "[version number]" or just simply pod "Alamofire"

Save the file and in your concluding practice a pod install, one time it has finished installation it should have created a Pods folder, [projectname].xcworkspace, and a Podfile.lock .

Save your podfile and run pod install
Salvage your podfile and run pod install

Open up the file named [projectname.xcworkspace] and your project should have Alamofire installed and set up to go

Open the xcworkspace file and check that the Alamofire libraries are there
Open the xcworkspace file and check that the Alamofire libraries are there

Role two: Using Alamofire

Uncomplicated Request

For this example we will exist using httpbin.org to simulate our http calls.

For starters permit's do a unproblematic Get asking, in your ViewController.swift type the post-obit:

An Alamofire request
An Alamofire request

Save and run the program, one time it runs information technology should impress out in the debug log like this

Debug output
Debug output

Its as simple as that!. There are also other HTTP Method calls like POST, PUT, DELETE, ETC.

To do and so its as uncomplicated as adding a method in the Alamofire request by using their already pre-congenital enums for information technology. Just simply type:

// Mail AF.request("https://httpbin.org/post", method: .post) // PUT AF.asking("https://httpbin.org/put", method: .put) // DELETE AF.request("https://httpbin.org/delete", method: .delete)        

Asking with Parameters

Non all HTTP Requests are evidently and simple, most pages need information like account data, folio information, category, etc. these can be easily washed in Alamofire by doing so:

let parameters = ["category": "Movies", "genre": "Activity"]          	AF.request("https://httpbin.org/get", parameters: parameters).response { response in             debugPrint(response)         	}  //this is equivalent to https://httpbin.org/become?category=Movies&genre=Action        

Nice and easy right?

HTTP Headers

Alamofire has its own back up for HTTP Headers which are a great way to let the client and the server pass boosted information with an HTTP request or response. It can be hands added to our Alamofire Request hands by just adding an HTTPHeaders value:

          allow headers: HTTPHeaders = [             .potency(username: "test@e-mail.com", password: "testpassword"),             .have("application/json")         ]          AF.request("https://httpbin.org/headers", headers: headers).responseJSON { response in             debugPrint(response)         }        

It can too be easily combined with other options like sending parameters:

let headers: HTTPHeaders = [             .authorisation(username: "test@email.com", password: "testpassword"),             .take("application/json")         ]  let parameters = ["category": "Movies", "genre": "Activity"]  AF.request("https://httpbin.org/headers", headers: headers, parameters: parameters).responseJSON { response in             debugPrint(response)         }        

Handling Say-so

There are a few means to handle authentication using Alamofire, ane of them is via Header as shown in the case above, the others are more direct or brand utilize of the URLCredential data type, here are some examples:

// Normal mode to authenticate using the .authenticate with username and password let user = "test@e-mail.com" allow password = "testpassword"  AF.request("https://httpbin.org/basic-auth/\(user)/\(countersign)")             .cosign(username: user, password: password)             .responseJSON { response in                 debugPrint(response)             }  	// Authentication using URLCredential  let credential = URLCredential(user: user, countersign: countersign, persistence: .forSession)                  AF.asking("https://httpbin.org/bones-auth/\(user)/\(password)")             .authenticate(with: credential)             .responseJSON { response in             debugPrint(response)             }        

Response Handling

Alamofire support unlike ways on how to handle a response. A response is expected  to provide the client with the resource it requested, or inform the customer that the action it requested has been carried out; or else to inform the client that an error occurred in processing its request.

Basic Response

This basic response does not evaluate any of the response data it just forwards information directly from URLSessionDelegate. Call up of it equally the Alamofire equivalent of cURL to execute a request.

AF.request("https://httpbin.org/go").response { response in     debugPrint("Response: \(response)") }        

JSON Response

The responseJSON handler uses a JSONResponseSerializer to convert the Data returned past the server into an Whatsoever type using the specified JSONSerialization.ReadingOptions.

AF.request("https://httpbin.org/get").responseJSON { response in     debugPrint("Response: \(response)") }        

Information Response

The responseData handler uses a DataResponseSerializer to extract and validate the Data returned by the server.

AF.asking("https://httpbin.org/get").responseData { response in     debugPrint("Response: \(response)") }        

String Response

The responseString handler uses a StringResponseSerializer to convert the Data returned by the server into a String with the specified encoding.

AF.request("https://httpbin.org/get").responseString { response in     debugPrint("Response: \(response)") }        

Decodable Response

The responseDecodable handler uses a DecodableResponseSerializer to convert the Data returned by the server into the passed Decodable blazon using the specified DataDecoder

struct HTTPBinResponse: Decodable { permit url: String }  AF.request("https://httpbin.org/get").responseDecodable(of: HTTPBinResponse.self) { response in    	     debugPrint("Response: \(response)") }        

File Download/Handling

Alamofire supports multiple ways of handling data, some data is fine by just fetching by memory, but for larger sets of data Session.download, DownloadRequest, and DownloadResponse is also supported.

Fetch in Memory

Basic fetching of an image by memory, it is not saved and volition require loading again if being fetched again.

AF.download("https://httpbin.org/image/png").responseData { response in             if permit data = response.value {                 self.imageView.image = UIImage(data: data)             }         	}        

Download locally

Alamofire supports downloading of file to go far easier to access, retrieve of information technology equally a re-create for faster loading like a cache:
=

          allow destination: DownloadRequest.Destination = { _, _ in             let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]             	allow fileURL = documentsURL.appendingPathComponent("image.png")              	return (fileURL, [.removePreviousFile, .createIntermediateDirectories])         }          AF.download("https://httpbin.org/epitome/png", to: destination).response { response in             debugPrint(response)              if response.mistake == nada, let imagePath = response.fileURL?.path {                 let image = UIImage(contentsOfFile: imagePath)             }         }        

Uploading Data/Files

Uploading information is somewhat like shooting fish in a barrel, you just need to specify what kind of Data you are sending and permit alamofire exercise the rest, it works the aforementioned as a Mail .

permit information = Data("data".utf8)  AF.upload(data, to: "https://httpbin.org/post").responseJSON { response in     debugPrint(response) }        


Information technology is too possible to send a multipart form data like so:

AF.upload(multipartFormData: { multipartFormData in     multipartFormData.append(Data("one".utf8), withName: "one")     multipartFormData.append(Data("two".utf8), withName: "two") }, to: "https://httpbin.org/mail service")     .responseJSON { response in         debugPrint(response) }        

You can also upload files via Alamofire by just specifying the file name and information technology'southward extension:

let fileURL = Parcel.main.url(forResource: "video", withExtension: "mp4")!  AF.upload(fileURL, to: "https://httpbin.org/postal service").responseJSON { response in     debugPrint(response) }        

Upload/Download Progress

Nosotros at present know that Alamofire supports both downloading and uploading of files, but how practice we track the progress of our upload/download every bit information technology happens? At that place is an option for that, only merely add a .downloadProgress or .uploadProgress but before your response similar then:

// For downloadProgress       let destination: DownloadRequest.Destination = { _, _ in             let documentsURL = FileManager.default.urls(for: .picturesDirectory, in: .userDomainMask)[0]             	let fileURL = documentsURL.appendingPathComponent("paradigm.png")              	render (fileURL, [.removePreviousFile, .createIntermediateDirectories])         }          AF.download("https://httpbin.org/epitome/png", to: destination) .downloadProgress { progress in        		 print("Download Progress: \(progress.fractionCompleted)")     	} .response { response in             debugPrint(response)              if response.fault == nil, let imagePath = response.fileURL?.path {                 let image = UIImage(contentsOfFile: imagePath)             }         }  // For uploadProgress   allow fileURL = Package.main.url(forResource: "video", withExtension: "mp4")!                 AF.upload(fileURL, to: "https://httpbin.org/mail")                 .uploadProgress { progress in                      print("Upload Progress: \(progress.fractionCompleted)")                 }                 .responseJSON { response in                     debugPrint(response.response)                }        

Conclusion

That's about it for this essential guide to Swift Alamofire, with these information you should be equipped plenty to use Alamofire in your swift project, if y'all ever need extra info you lot can check out the official guide and documentation here. Proficient luck and accept fun coding! 🙂


Further Reading

  • CocoaPods Tutorial using Swift and Xcode: Learn how to install and use Cocoapods in your Xcode project! Take advantage of tertiary party Swift libraries and GitHub repositories hands.
  • How To Utilise SwiftyJSON: SwiftyJSON is a Swift library for reading and processing JSON data. Larn how easy information technology is to apply information technology and how it'due south unlike from Codable and JSONSerialization
  • How To Submit Your App To the App Store: Acquire how to submit your app to the App Store with App Shop Connect the right way!

nashbrilivele.blogspot.com

Source: https://codewithchris.com/alamofire/

0 Response to "Alamofire 4 Multipart Form Data Video Upload"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel