当前位置:网站首页>Afnetworking crash course
Afnetworking crash course
2022-07-28 14:26:00 【51CTO】
AFNetworking Crash course
The Internet — Your program cannot survive without it ! Apple Foundation framework Medium NSURLConnection And very difficult to understand , However, there is an alternative that can be used : AFNetworking.
AFNetworking Very popular with developers – It has won the favor of our readers :2012 The best iOS Library prize ( 2012 Best iOS Library Award.) So now I will write this article to introduce you how to use it effectively in the program .
AFNetworking It includes all the content you need to interact with online resources , from web services To file download . When your program is downloading a large file ,AFNetworking It can also ensure your UI Is responsive .
This article will introduce AFNetworking The main components of the framework . Along the way , You will use World Weather Online Advice provided (Feeds) To create a weather (Weather) Program . The weather data used at the beginning is static , But after learning the content of this article , The program will be connected to real-time weather consultation .
Expected today : A cool developer learns all about AFNetworking knowledge , And use in his program AFNetworking. Let's get busy !
Start
First come here ( here) Download the startup project for this article . This project provides a basic UI — AFNetworking The relevant code has not been added .
open MainStoryboard.storyboard file , Will see 3 individual view controller:
From left to right , Namely :
- top (top-level) Navigation controller for ;
- Used to display the weather table view controller, One line a day ;
- A custom view controller (WeatherAnimationViewController) When a user clicks on a table view cell when , This view controller The weather consultation of a certain day will be displayed .
Build and run the project , You will see relevant UI appear , But nothing has been achieved ! Because the program needs to get the required data from the network , The relevant code has not been added . This is what you will achieve in this article !
First , You need to AFNetworking The framework is included in the project . If you haven't AFNetworking Words , Download the latest version here : GitHub.
When you unzip the downloaded file , You will see one of them AFNetworking A folder , Full of .h and .m file , Highlighted below :
take AFNetworking Drag and drop to Xcode In Engineering .
When the option to add a file appears , Make sure that... Is checked Copy items into destination group’s folder (if needed) and Create groups for any added folders.
To complete the relevant configuration , Please work in Supporting Files Open the precompiled header file in the Group Weather-Prefix.pch. And then in other import Add the following line of code after :
take AFNetworking Add to precompiled header file , This means that the framework will be automatically added to all source code files of the project .
be prone to , isn't it? ? Now you're ready “ The weather ” Program code !
operation JSON
AFNetworking It is very intelligent to load and process structured data through the network , ordinary HTTP The same is true of requests . In particular, it supports JSON, XML and Property Lists (plists).
You can download some JSON data , Then use your own parser to parse , But why this ? adopt AFNetworking You can complete these operations !
First , You need to test the script ( data ) A basic requirement URL. Put the following static NSString Declare to WTTableViewController.m Top , That's all #import below :
This URL It's a very simple one “web service”, In this article, I specially created for you . If you want to know what it looks like , You can download the code here : download the source.
This web service With 3 Different formats (JSON, XML and PLIST) Return weather data . You can use the following URL Take a look at the returned data :
- http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=json
- http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=xml
- http://www.raywenderlich.com/downloads/weather_sample/weather.php?format=plist (might not show up right in your browser)
The first data format uses JSON. JSON It is a common JavaScript Derived class object format . It looks like :
Be careful : If you want to tie more about JSON Content , Please refer to : Working with JSON in iOS 5 Tutorial.
When the user clicks JSON Button , What you want from the service JSON Data is loaded and processed . stay WTTableViewController.m in , find jsonTapped: Method ( It should be empty now ) , And replace with the following code :
This is your first AFNetworking Code ! therefore , It looks brand new , I will introduce the code in this method .
- According to the basic URL Construct a complete URL. Then through this complete URL To obtain a NSURL object , And then according to this url To obtain a NSURLRequest.
- AFJSONRequestOperation Is a fully functional class (all-in-one)— It integrates the acquisition of data from the network and JSON To analyze .
- When the request is successful , Then run the successful block (success block). In this example , Analyze the weather data from JSON The variable is converted to a dictionary (dictionary), And store it in the attribute weather in .
- If something goes wrong , Then run the failed block (failure block), For example, the network is unavailable . If failure block Is called the , The error message will be displayed through the prompt box .
As shown above ,AFNetworking Is very simple to use . If you want to use what Apple provides APIs( Such as NSURLConnection) To do the same thing ( Download and parse JSON data ), It takes a lot of code to do .
Now the weather data already exists in self.weather in , You need to show it . find tableView:numberOfRowsInSection: Method , And replace with the following code :
table view There are two section: The first one is used to display the current weather , The second one is used to show the future weather .
Wait a minute , You may be thinking . there [self.weather upcomingWeather] What is it? ? If self.weather It's a common NSDictionary, How does it know “upcomingWeather” What is it? ?
In order to analyze the data more easily , stay starter In Engineering , There is a pair of NSDictionary categories:
- NSDictionary+weather.m
- NSDictionary+weather_package.m
these categories Added some convenient methods , Through these methods, you can easily access the data elements in the dictionary . So you can focus on the network , instead of NSDictionary Data access in . Right ?
go back to WTTableViewController.m, find tableView:cellForRowAtIndexPath: Method , And replace with the following implementation :
Follow tableView:numberOfRowsInSection: The method is the same , Convenient... Is used here NSDictionary categories To get the data . The weather of the current day is a dictionary , The weather of the next few days is stored in an array .
Generate and run the project , And then click JSON Button . This will dynamically get a AFJSONOperation object , And see the following picture :
JSON Successful operation !
operation Property Lists(plists)
Property lists ( Or for short plists) In a certain format ( Apple defines ) Composed of XML file . Apples will generally plists Used in user settings . It looks like :
It means :
- A dictionary has a name “data” Of key, This key Corresponding to another dictionary .
- This dictionary has a name “current_condition” Of key, This key Corresponding to a array.
- This array contains a dictionary , There are many in the dictionary key and values. such as cloudcover=16 and humidity=59.
Now it's time to load plist Version of the weather data ! find plistTapped: Method , And replace with the following implementation :
be aware , The above code is almost the same as JSON Consistency of version , It's just going to operate (operation) Type from AFJSONOperation It is amended as follows AFPropertyListOperation. This is very neat : You just need to modify a little bit of code to receive JSON or plist Data in format !
Generate and run the project , And then click PLIST Button . You will see the following :
If you need to reset everything , To restart the operation , At the top of the navigation bar Clear The button can be cleared title and table view Data in .
operation XML
AFNetworking Handle JSON and plist The parsing of uses a similar method , It doesn't take much effort , And deal with XML It's a little more complicated . below , According to XML Consult to build a weather dictionary (NSDictionary).
iOS Provides a help class :NSXMLParse ( If you want to know more , Please see the link here : SAX parser).
Still in the file WTTableViewController.m, find xmlTapped: Method , And replace with the following implementation :
Up to now , This seems to be the same as the previous treatment JSON and plist Is very similar . The biggest change is in the success block (success block) in , It will not pass you a preprocessed NSDictionary object . It is AFXMLRequestOperation Instantiated NSXMLParse object , This object will be used to handle heavy XML Parsing tasks .
NSXMLParse Object has a group delegate Method is what you need to achieve — Used to obtain XML data . Be careful , In the above code, I will XMLParser Of delegate Set to self, therefore WTTableViewController Will be used to deal with XML The parsing task of .
First , Update WTTableViewController.h And modify the class declaration , As shown below :
The above code means that this class will implement ( follow )NSXMLParserDelegate agreement . The next step will be the following delegate Method declarations are added to @implementation Back :
In order to support the analysis of information , You also need some attributes to store relevant data . Add the following code to @implementatio Back :
Then open WTTableViewController.m, Now you need to implement the above mentioned ones one by one delegate Method . Paste the following method into the implementation file :
When NSXMLParser When a new element start tag is found , Will call the above method . In this method , Construct a new dictionary to store the assigned value to currentDictionary Properties before , First save the last element name . Try to make outstring Reset , This string is used to construct XML The data in the tag .
Then paste the following method behind the previous method :
Like the name , When NSXMLParser In a XML Character data found in tag , Will call this method . This method appends character data to outstring Properties of the , When XML At the end of the tag , This outstring Will be dealt with .
continue , Paste the following method behind the previous method :
When the end tag of the element is detected , Will call the above method . In this method , Will find some tags :
- urrent_condition The element represents the weather of today . Today's weather will be added directly to xmlWeather In the dictionary .
- weather The element represents the weather of the next day . There is only one weather today , And the following weather has many , So here , Add the subsequent weather to an array .
- value Tags appear in other tags , So this label can be ignored here .
- weatherDesc and weatherIconUrl The value of the element is stored before , Need to be put into an array — The structure here is to connect with JSON and plist The version of the weather advisory format matches .
- All other elements are as is (as-is) stored .
Here is the last one delegate Method ! Paste the following method behind the previous method :
When NSXMLParser Resolved to document At the end of , Will call this method . Here it is ,xmlWeather The dictionary has been constructed ,table view It can be reloaded .
In the above code xmlWeather Add to a dictionary , It seems redundant , However, this can ensure that JSON and plist The format of the version exactly matches . So all of 3 Data formats (JSON, plist and XML) Can be displayed with the same code !
Now all of delegate Methods and properties are all done , find xmlTapped: Method , And uncomment the successful block (success block) One line of code in :
Generate and run projects , And then click XML Button , You will see the following :
A small weather program
Um. , The above program doesn't seem to have a friendly experience , It's a bit like rainy days all week . How to make table view The weather information experience in is better ?
Take a closer look at the previous JSON Format data : JSON format from before, You will see a picture in each weather item URLs. Show these weather pictures to each table view cell in , In this way, the program will look more interesting .
AFNetworking to UIImageView Added a category, Make pictures load asynchronously , That is to say, when the pictures are downloaded in the background , programmatic UI The interface is still responsive . To use this function , First, you need to put this category import To WTTableViewController.m Top of file :
First create a weak reference (weak) Of cell, So you can do it block Use this cell. If you visit directly cell Variable ,Xcode There will be a prompt about retain Warnings of loops and memory leaks .
UIImageView+AFNetworking category Defined a setImageWithURLRequest… Method . The parameters of this method include : A pointing image URL Request , A placeholder picture , One success block And a failure block.
When cell When it was first created ,cell Medium UIImageView A placeholder image will be displayed , Until the real image is downloaded . Here you need to make sure that the placeholder image is the same size as the actual image .
If the dimensions are different , You can success block Call in cell Of setNeedsLayout Method . Two lines of code are commented in the above code , This is because the placeholder image here is just the right size , Leave notes , It may be used in other programs .
Now generate and run the project , Then click on the previously added 3 Any of the operations , You will see the following :
very good ! Loading pictures asynchronously has never been easier .
One RESTful class
Up to now, you have used similar AFJSONRequestOperation Such a class creates a one-time HTTP request . in addition , Lower level AFHTTPClient Class is used to access a single web service terminal . For this AFHTTPClient It is usually set with a basic URL, And then use AFHTTPClient Make multiple requests ( Not like before , Every time I ask , all Create a AFHTTPClient).
AFHTTPClient It is also the coding parameter 、 Handle multipart Form request body Construction 、 Managing request operations and batch queueing operations provides great flexibility , It also Handled the whole set RESTful (GET, POST, PUT, and DELETE), Now let's try the two most commonly used :GET and POST.
Be careful : Yes REST, GET and POST Unclear ? Take a look at the interesting introduction here – How can I explain to my wife REST( How I Explained REST to My Wife.)
stay WTTableViewController.h At the top, modify the class declaration as follows :
stay WTTableViewController.m in , find httpClientTapped: Method , And replace with the following implementation :
The above method will pop up a action sheet, To select GET and POST request . Paste the following code to achieve action sheet The corresponding operation of the button in :
The above code works as follows :
- Construct a baseURL, And a parameter dictionary , And pass these two variables to AFHTTPClient.
- take AFJSONRequestOperation register as HTTP The operation of , In this way, it can be the same as the previous example , You can get parsed JSON data .
- Made a GET request , This request has a pair block:success and failure.
- POST Please follow GET equally .
ad locum , Will request a JSON Respond , Of course, you can also use the other two formats discussed before to replace JSON.
Generate and run the project , Click on HTTPClient Button , And then choose GET or POST Button to initialize a related request . Then you will see the following :
thus , You already know AFHTTPClient The most basic way to use . however , There is a better way to use it , It can make the code cleaner and tidier , Let's learn about it .
Connect to Live Service
Up to now , You are already in table view controller Called directly in AFRequestOperations and AFHTTPClient. actually , Most of the time it's not like this , Your network request will be with someone web service or API relevant .
AFHTTPClient Have the ability to communicate with web API All contents of the communication .AFHTTPClient The network communication part has been coupled in the code , The code of network communication can be reused in the whole project .
Here are two questions about AFHTTPClient Best practice guidance :
- For each web service Create a subclass . for example , If you are writing a social network aggregator , Then maybe there will be Twitter A subclass of ,Facebook A subclass of ,Instragram And so on .
- stay AFHTTPClient In subclass , Create a class method , Used to return a shared singleton , This will save resources and save the necessary object creation .
At present , There is no one in your project AFHTTPClient Subclasses of , Now let's create one . Let's deal with it , Let the code clean up .
First , Create a new file in the project :iOSCocoa TouchObjective-C Class. Name it WeatherHTTPClient And let it inherit from AFHTTPClient.
You want this class to do 3 thing :
A: perform HTTP request
B: When new weather data is available , call delegate
C: Use the user's current geographical location to get accurate weather .
Replace with the following code WeatherHTTPClient.h:
In the implementation file , You will learn more about the definition in the header file . open WeatherHTTPClient.m And add the following code to @implementation below :
sharedWeatherHTTPClient Methods use Grand Central Dispatch(GCD) To ensure that the shared singleton object is initialized and allocated only once . I'm going to use a base URL To initialize the object , And set it as expected web service The response is a JSON.
Paste the following method under the previous method :
This method calls World Weather Online Interface , To get the weather information of the specific location .
It's very important ! In this example API key Just created for this article . If you create a program , Please be there. World Weather Online Create an account , And get your own API key!
Once the object obtains the weather data , It needs some way to inform the interested objects : The data is back . Thank you here WeatherHttpClientDelegate Agreement and its delegate Method , In the code above success and failure blocks You can inform one controller: The weather at the designated location has been updated . such ,controller You can update the weather .
Now? , We need to integrate these code fragments !WeatherHTTPClient Want to receive a location information , also WeatherHTTPClient Definition One. delegate agreement , Right now WTTableViewControlle Class to update , To use the WeatherHTTPClient.
open WTTableViewController.h Add one import, And replace with the following code @interface Statement :
Add a new Core Location manager attribute :
stay WTTableViewController.m in , Add the following code to viewDidLoad: The bottom of :
The above two lines of code initialize Core Location manager, So when view When loading , Used to determine the current location of the user .Core Location And then it will pass delegate Callback to return location information . Add the following method to the implementation file :
Now? , When the user's location changes , You can use it WeatherHTTPClient Single example to request the weather information of the current location .
remember ,WeatherHTTPClient There are two delegate Method needs to implement . Add the following two methods to the implementation file :
The above two methods , When WeatherHTTPClient The request is successful , You can update the weather data and reload table view. If the network is wrong , An error message is displayed .
find apiTapped: Method , And replace with the following method :
Build and run programs , Click on AP Button to initialize a WeatherHTTPClient request , Then you will see the following picture :
I hope your future weather here is the same as mine : a sunny day !
I'm not dead yet !
You may have noticed , The external call here web service It takes some time to return data . When operating on the network , It is very important to provide users with an information feedback , Only in this way can users know whether the program is running or has crashed .
Fortunately ,AFNetworking There is a simple way to provide feedback :AFNetworkActivityIndicatorManager.
stay WTAppDelegate.m in , find application:didFinishLaunchingWithOptions: Method , And replace with the following method :
Give Way sharedManager It can automatically display the network activity indicator ( network activity indicator)— Whenever you shoot , As long as there is a new network request running in the background . So you don't have to ask every time , Should be managed separately .
Generate and run the project , whenever , As long as there is a network request , You can see a small network fire wheel in the status bar :
Now? , Even if your program is waiting for a slow web service, Users know that the program is still running !
Download the pictures
If you are in the table view cell Click on , The program will switch to the detailed picture of the weather , And the corresponding weather conditions are displayed in an animated way .
This is very good , But at present, there is only one background image in animation . In addition to updating the background image through the network , Is there a better way !
The following is the introduction of this article AFNetworking The last content of :AFImageRequestOperation. Follow AFJSONRequestOperation equally , AFImageRequestOperation Encapsulates the HTTP request : Get photo .
stay WeatherAnimationViewController.m There are two methods that need to be implemented . find updateBackgroundImage: Method , And replace with the following code :
This method initializes and downloads a new background image . At the end , It will return the requested complete picture .
stay WeatherAnimationViewController.m in , You will see two auxiliary methods :imageWithFilename: and saveImage:withFilename:, Through these two auxiliary methods , You can store and load the downloaded pictures .updateBackgroundImage: The downloaded pictures will be stored on disk through auxiliary methods .
Next find deleteBackgroundImage: Method , And replace with the following code :
This method will delete the downloaded pictures , So when testing the program , You can download the pictures again .
The last time : Generate and run the project , Download weather data , And click a cell, To open the detailed weather screen . In the detailed weather picture , Click on Update Background Button . If you click sunny cell, You will see the following picture :
come from :http://www.raywenderlich.com/zh-hans/36079/afnetworking
7
边栏推荐
- 【Utils】JsonUtil
- 草料二维码--在线二维码生成器
- Custom Configuration Sections
- Redis sentinel mechanism
- Mobile phone scrolling screenshot software recommendation
- [lvgl events] Application of events on different components (I)
- Thoughts on the construction of some enterprise data platforms
- Another way of understanding the essence of Hamming code
- 7.27 simulation summary
- HCIP第十一天
猜你喜欢

MySQL development skills - View

MiniTest--小程序自动化测试框架

HCIP第十二天

Tdengine helps Siemens' lightweight digital solutions

Clickhouse架构与设计

These three online PS tools should be tried

Xcode编写SwiftUI代码时一个编译通过但导致预览(Preview)崩溃的小陷阱

Thoughts on the construction of some enterprise data platforms

Solve the problem that uniapp wechat applet canvas cannot introduce fonts

软件测试的发展与定义
随机推荐
Nport serial server configuration website (whether the serial server is from network port to serial port)
Open source project - taier1.2 release, new workflow, tenant binding simplification and other functions
Literature reading (245) roller
如何有效进行回顾会议(上)?
Target detection: speed and accuracy comparison (fater r-cnn, r-fcn, SSD, FPN, retinanet and yolov3)
Brief introduction of diversity technology
树莓派基础 | 总结记录树莓派学习过程中的一些操作
bgp实验
MySQL development skills - View
Cv:: mat conversion to qimage error
How does vos3000 send incoming calls to okcc
2022年熔化焊接与热切割考题及在线模拟考试
Copy excel row to specified row
Leetcode 105. construct binary tree from preorder and inorder traversal sequence & 106. construct binary tree from inorder and postorder traversal sequence
js的实例化方式
Career planning of Software Test Engineer
开源项目丨Taier1.2版本发布,新增工作流、租户绑定简化等多项功能
PowerDesigner creates a database model (conceptual model example)
[ecmascript6] set and map
朗镜科技(Trax中国)“机器人+AI”开启中国零售元宇宙时代