This is the 30th day of my participation in the Wenwen Challenge
preface
Since I simply learned how to write code on the Playground, SWIFT has made me more enthusiastic about learning. Learn more about Swift’s advanced features, Closures, Codable, Mirror, Combine, and basic String, Class, and Function.
However, when I learned to Combine+Networking, I encountered a crazy problem: I could not get the response result of the asynchronous network request I wrote. At the beginning, I suspected that there was something wrong with the Combine written by me. After all, I just learned Combine. Combine is a substitute for RX Swift, and it is difficult to learn. Here is my code
var storage = Set<AnyCancellable> ()let url = URL(string:"https://jsonplaceholder.typicode.com/posts/1")!
URLSession.shared.dataTaskPublisher(for: url).map { tuple -> Data in / / the tuple type (data: data, the response: URLResponse)
// print("tuple:\(tuple)")
return tuple.data
}.sink { completion in
print(completion)
} receiveValue: { data in
print(data.description)
let resonpseStr = String(data: data, encoding: .utf8)
print("Print data:\(resonpseStr)")
}.store(in: &storage)
Copy the code
The code could not have been a simpler request, but the data print data: was never executed
Guess: After Playground is done, the object is freed, so no asynchronous callback is available
The back does prove my idea is right!
Through baidu + Google there are indeed many people who have encountered the same problem;
Here’s why:
Execute asynchronously in Playground
The code in the Playground is top-level code, meaning that it is in global scope. The code is executed from top to bottom and stops immediately after execution.
Our asynchronous callback code generally doesn’t get executed before the program ends, so if we do networking on Playground, or any other time-consuming asynchronous operation, we won’t get the results we want
To allow the program to continue after the end of code execution, we can use the following code:
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
Copy the code
This code will make the Playground perform forever, when we get the result of the need, can use XCPlaygroundPage. CurrentPage. FinishExecution () to stop the execution of the Playground:
To solve the problem
Fix our network code
import Foundation
import Combine
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
var storage = Set<AnyCancellable> ()let url = URL(string:"https://jsonplaceholder.typicode.com/posts/1")!
URLSession.shared.dataTaskPublisher(for: url).map { tuple -> Data in / / the tuple type (data: data, the response: URLResponse)
// print("tuple:\(tuple)")
return tuple.data
}.sink { completion in
print(completion)
} receiveValue: { data in
print(data.description)
let resonpseStr = String(data: data, encoding: .utf8)
print("Print data:\(resonpseStr)")
// Call the end loop in an asynchronous callback
PlaygroundPage.current.finishExecution()
}.store(in: &storage)
Copy the code
Network data is successfully obtained. Procedure
[Combine.AnyCancellable]
292 bytes
data:Optional("{\n \"userId\": 1,\n \"id\": 1,\n \"title\": \"sunt aut facere repellat provident occaecati excepturi optio reprehenderit\",\n \"body\": \"quia et suscipit\\nsuscipit recusandae consequuntur expedita et cum\\nreprehenderit molestiae ut ut quas totam\\nnostrum rerum est autem sunt rem eveniet architecto\"\n}")
Copy the code
Pay attention to remember the import import PlaygroundSupport, in an asynchronous callback PlaygroundPage. Current. FinishExecution end loop ()
conclusion
There are plenty of other advanced features in Playground that are worth exploring. Dig a hole for yourself and give yourself a full tutorial on how to use Playground.
A small speech
It’s hard to imagine this being my 30th day in a row. Especially for me, who didn’t have any article stock and was a new dad, it was really painful to insist at the beginning. I could only wait for my baby to sleep and force myself to make a summary of the day’s learning or learn new skills to share. But looking back on it, every day is actually more fulfilling. There are fewer opportunities to fish, more time to think seriously, and even the speed and accuracy of typing have improved. Thank you to the Nuggets for initiating this program. I will update and share the articles from time to time. After all, writing articles is no longer a terrible thing for me.
reference
www.jianshu.com/p/8b37c3ef6…