NSURLSession สำหรับการเรียก API
ใช้ NSURLSession เพื่อส่งคำขอเครือข่าย จัดการคำตอบ และถ่ายโอนข้อมูลกับ API แบบ RESTful
NSURLSession สำหรับการเรียก API เป็นบทเรียน Objective-C iOS Development for Legacy & Enterprise Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Objective-C iOS Development for Legacy & Enterprise Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Objective-C iOS Development for Legacy & Enterprise Apps มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Connecting Your App to the World
Mobile apps often need to talk to the internet to fetch or send data. This is called networking.
Think of checking the weather, loading your social media feed, or sending a message. All these involve your app making requests to a server.
Servers expose APIs (Application Programming Interfaces), which are sets of rules for how your app can interact with them. Many modern APIs follow the REST architectural style.
Meet NSURLSession
In Objective-C, the primary way to perform network requests is using NSURLSession. It's a powerful and flexible API for downloading content over HTTP/HTTPS.
- It replaced older methods like
NSURLConnection. - It handles data tasks, download tasks, and upload tasks.
- It supports background transfers and authentication.
NSURLSession makes network communication more efficient and easier to manage.
NSURLSession's Building Blocks
NSURLSession works with a few key components:
NSURLSession: The main object that coordinates network tasks.NSURLSessionConfiguration: Defines the behavior of a session (e.g., caching, timeouts, cellular access).NSURLSessionTask: An abstract class for tasks. Concrete subclasses includeNSURLSessionDataTask(for data),NSURLSessionDownloadTask(for files), andNSURLSessionUploadTask(for uploading files).
Making a Simple GET Request
Let's make a basic GET request to fetch data from a server. A GET request is used to retrieve information.
We'll use NSURLSessionDataTask. This task takes a URL and a completion handler (a block of code) that runs when the request finishes.
Remember to call [task resume]; to start the task!
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// 1. Create a URL
NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/todos/1"];
// 2. Create a session (using the default shared session)
NSURLSession *session = [NSURLSession sharedSession];
// 3. Create a data task
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
} else {
// Check for HTTP status code (e.g., 200 OK)
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"Response Data: %@", responseString);
} else {
NSLog(@"Server returned status code: %ld", (long)httpResponse.statusCode);
}
}
CFRunLoopStop(CFRunLoopGetCurrent()); // Stop the run loop once task finishes
}];
// 4. Start the task
[dataTask resume];
// Keep the main thread alive until the async task completes
CFRunLoopRun();
}
return 0;
}Understanding the Response
The completion handler block for a data task provides three parameters:
data: The raw data received from the server (e.g., JSON, image bytes).response: AnNSURLResponseobject, which can be cast toNSHTTPURLResponsefor HTTP-specific details like status codes (200 OK, 404 Not Found, etc.) and headers.error: AnNSErrorobject if something went wrong during the request (e.g., no internet connection, server unreachable).
Always check for error first, then the HTTP status code.
Decoding JSON Responses
Most REST APIs return data in JSON (JavaScript Object Notation) format. This is a lightweight, human-readable data interchange format.
Objective-C provides NSJSONSerialization to convert raw NSData into Objective-C objects (NSDictionary or NSArray) and vice-versa.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/todos/1"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSError *jsonError = nil;
// Attempt to parse JSON data
id jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0 // No special options
error:&jsonError];
if (jsonError) {
NSLog(@"JSON Parsing Error: %@", jsonError.localizedDescription);
} else if ([jsonObject isKindOfClass:[NSDictionary class]]) {
NSDictionary *todoItem = (NSDictionary *)jsonObject;
NSLog(@"Todo Title: %@", todoItem[@"title"]);
NSLog(@"Completed: %@", todoItem[@"completed"] ? @"YES" : @"NO");
} else {
NSLog(@"Received unexpected JSON format.");
}
} else {
NSLog(@"Server returned status code: %ld", (long)httpResponse.statusCode);
}
}
CFRunLoopStop(CFRunLoopGetCurrent());
}];
[dataTask resume];
CFRunLoopRun();
}
return 0;
}Tailoring NSURLSession with Configuration
For more control, you can create a custom NSURLSession using an NSURLSessionConfiguration object.
Common configurations include:
defaultSessionConfiguration: Uses a global shared cookie storage, credential storage, and disk-based cache.ephemeralSessionConfiguration: Similar to default, but stores no data to disk (e.g., no caches, cookies). Ideal for private browsing.backgroundSessionConfigurationWithIdentifier:: Allows transfers to continue when your app is suspended or terminated.
You can set properties like timeoutIntervalForRequest, HTTPAdditionalHeaders, and more.
Sending Data with POST
While GET retrieves data, POST requests are used to send new data to the server (e.g., submitting a form, creating a new resource).
For POST, you typically create an NSURLRequest object, set its HTTP method to "POST", and attach the data you want to send as HTTPBody.
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSURL *url = [NSURL URLWithString:@"https://jsonplaceholder.typicode.com/posts"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
request.HTTPMethod = @"POST"; // Set HTTP method to POST
// Prepare data to send (e.g., a new post title and body)
NSDictionary *postData = @{
@"title": @"foo",
@"body": @"bar",
@"userId": @1
};
NSError *jsonError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postData options:0 error:&jsonError];
if (jsonError) {
NSLog(@"JSON serialization error: %@", jsonError.localizedDescription);
CFRunLoopStop(CFRunLoopGetCurrent());
return 1;
}
request.HTTPBody = jsonData;
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode >= 200 && httpResponse.statusCode < 300) {
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"POST Success! Response: %@", responseString);
} else {
NSLog(@"Server returned status code: %ld", (long)httpResponse.statusCode);
}
}
CFRunLoopStop(CFRunLoopGetCurrent());
}];
[dataTask resume];
CFRunLoopRun();
}
return 0;
}Handling Network Errors Gracefully
Network requests can fail for many reasons. Robust error handling is crucial for a good user experience.
- Check the
errorobject first: This indicates fundamental issues like no internet, DNS lookup failure, or server connection problems. - Check
NSHTTPURLResponsestatus code: After confirming noerror, check the HTTP status code (e.g., 400 Bad Request, 401 Unauthorized, 500 Internal Server Error). - Provide user feedback: Inform the user about the issue, e.g., "No internet connection" or "Could not load data."
Always assume network requests can fail and plan for it!
Quick Check: NSURLSession
Consider the following Objective-C code snippet for a network request:
NSURL *url = [NSURL URLWithString:@"https://example.com/data"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(@"Failed with error: %@", error.localizedDescription);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200) {
NSLog(@"Data received!");
} else {
NSLog(@"HTTP Status: %ld", (long)httpResponse.statusCode);
}
}
}];
// Missing line hereRecap: Mastering NSURLSession
In this lesson, we explored how to perform network requests using NSURLSession in Objective-C.
- We learned about
NSURLSession,NSURLSessionConfiguration, andNSURLSessionTask. - You can make GET requests to fetch data and POST requests to send data.
- We covered how to handle the response, including checking for errors and parsing JSON data using
NSJSONSerialization. - Always remember to call
[task resume];to start a task and implement robust error handling.
Next, you'll dive into concurrency with Grand Central Dispatch to keep your UI responsive during network operations!
คำถามที่พบบ่อย
บทเรียน “NSURLSession สำหรับการเรียก API” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “NSURLSession สำหรับการเรียก API” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Objective-C iOS Development for Legacy & Enterprise Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Objective-C iOS Development for Legacy & Enterprise Apps มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “NSURLSession สำหรับการเรียก API”
ใช้ NSURLSession เพื่อส่งคำขอเครือข่าย จัดการคำตอบ และถ่ายโอนข้อมูลกับ API แบบ RESTful คุณปฏิบัติ Objective-C iOS Development for Legacy & Enterprise Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Objective-C iOS Development for Legacy & Enterprise Apps หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน Objective-C iOS Development for Legacy & Enterprise Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “NSURLSession สำหรับการเรียก API” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน Objective-C iOS Development for Legacy & Enterprise Apps นี้ได้ไหม
ได้ บทเรียน Objective-C iOS Development for Legacy & Enterprise Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- NSURLSession สำหรับการเรียก API
- Grand Central Dispatch (GCD)
- NSOperationQueue สำหรับงานที่ซับซ้อน
- การแยกวิเคราะห์ JSON ด้วย NSJSONSerialization