Use async/await with URLSession

RSS for tag

Discuss the WWDC21 session Use async/await with URLSession.

View Session

Posts under wwdc21-10095 tag

15 Posts
Sort by:
Post not yet marked as solved
0 Replies
136 Views
CFURLEnumeratorGetNextURL search for next file. If my folder name has "#" it is not searching file correctly. When I closely analysed using CFErrorCopyUserInfo function, I got a dictionary that has different NSURLErrorKey and NSFilePathErrorKey. What is the difference between both the error keys. The file is correctly present at NSURL' s value. How does it get the value of NSFilePathErrorKey.
Posted
by
Post not yet marked as solved
3 Replies
383 Views
I have this data { "data":{ "date":"07-03-2022", "type":"airplane"  } } and my code is struct JsonResult: View{     enum LoadingState {            case idle, loading, loaded(UserData), failure(Error)        } @State private var state : LoadingState = .idle    var body: some View {      VStack {          switch state {              case .idle: EmptyView()              case .loading: ProgressView()              case .loaded(let userData):                                    VStack(alignment: .leading) {                      Text(userData.date)                          .font(.headline)                      Text(userData.type)                          .font(.headline)                  }                                case .failure(let error): Text(error.localizedDescription)          }      }.task {          await loadData()      }  }     struct Response: Encodable, Decodable {         var data: UserData     }     struct UserData: Codable {         var date: String         var type: String         private enum CodingKeys: String, CodingKey {             case date = "date"             case type = "type"         }     }         func loadData() async {            state = .loading      guard let url = URL(string: "MyUrl(related to cloud functions") else {          state = .failure(URLError(.badURL))          return      }      do {          let (data,_) = try await URLSession.shared.data(from: url)          // more code          let decodedResponse = try JSONDecoder().decode(Response.self, from: data)          state = .loaded(decodedResponse.data)                } catch {          state = .failure(error)          print(error) // this shows the real DecodingError      }  } } and after all this work, i want to get data from cloud functions, I got the same error, "The given data was not valid JSON.", although the data structure is valid json but It says data was not valid json ! any solution ? Thank you alot
Posted
by
Post not yet marked as solved
0 Replies
312 Views
For the following example I'm expecting if one of the concurrent tasks has thrown an error, the rest unfinished tasks must be cancelled. But it isn't what I see. If task2 has thrown first, the task1 will continue execution till completion. But it works as expecting in vice-verse, failing task1 first, results task2 cancellation. The log in case if task2 has thrown first: task1 BEGIN task2 BEGIN task2 completed task2 catch CancellationError() task2 END task1 completed // It's not expecting to see this log task1 catch CancellationError() task1 END Failed: CancellationError() The log in case if task1 has thrown first (works as expected, see there is no 'task2 completed' log. As soon as task1 has thrown, the entire try await(,) throws as well.): task1 BEGIN task2 BEGIN task1 completed task1 catch CancellationError() task1 END Failed: CancellationError() task2 catch CancellationError() task2 END Code is below: async let t1 = task1() async let t2 = task2() do { _ = try await (t1, t2) } catch { print("Failed: \(error)") } func task1() async throws -> Int {     print("task1 BEGIN")     defer { print("task1 END") }     do {       try await Task.sleep(nanoseconds: UInt64(3 * 1_000_000_000))       print("task1 completed")       throw CancellationError()     } catch {       print("task1 catch \(error)")       throw error     } } func task2() async throws -> Int {     print("task2 BEGIN")     defer { print("task2 END") }     do {       try await Task.sleep(nanoseconds: UInt64(1 * 1_000_000_000))       print("task2 completed")       throw CancellationError()     } catch {       print("task2 catch \(error)")       throw error     } }
Posted
by
Post marked as solved
1 Replies
249 Views
I have a table to which I've added a refreshControl and when I pull down the table to refresh the data, I reset the array that feeds the table with data and then immediately request new data through an API call. Until now, I have used completion handlers and protocols to get the data into the table view but I want to move the logic to async/await because of the complexity needed by the network calls and the pyramid of nested closures. Populating the view in viewDidLoad works fine but with pullToRefresh selector I get an error: Thread 1: EXC_BAD_ACCESS (code=1, address=0xbcf917df8160) override func viewDidLoad() {     super.viewDidLoad()     setupView()     setupTableView()     setupTableRefreshControl()     Task {       await getBalances() //async network call       myTable.reloadData()     }   }    func setupTableRefreshControl() {     myTable.refreshControl = UIRefreshControl()     myTable.refreshControl?.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)   } Code that crashes app:    @objc func didPullToRefresh() async {     balance.reset() // reset array to []     Task {       await getBalances() //async network call       myTable.reloadData()     }   }
Posted
by
Post not yet marked as solved
0 Replies
186 Views
Hi, Very new to ios and not aure what i am talking about, but happy to learn. I have an app that run an embedded survey. At submission the survey will do a redirect to apple store for app review. This is not working. Also tried to place a hyperlink to manualy redirect and not working. It just does not react. Any ideas where to start? Thanks.
Posted
by
Post not yet marked as solved
0 Replies
316 Views
I am developing one voIP application in which I have to register to the server every 60 minutes. Register consists of two parts, HTTP request to web server. Some other tasks in another server. During initial login, I am getting access token and refresh token. Access token has a validity of 48 hours. Every one hour I get push notifications from server for which I have to do registration. Also I request for access token using refresh token on the push notifications I get on 45th, 46th and 47th hours so that my access token remain valid. Everything works fine. Access token, login, register to server. After 48 hours getting Access token using Refresh token also works good most of the time. But sometimes for getting access token using refresh token I am getting the following error, Error Domain=org.openid.appauth.general Code=-5 "Connection error making token request to ‘’: The Internet connection appears to be offline.." UserInfo={NSLocalizedDescription=Connection error making token request to ‘**/mga/sps/oauth/oauth20/token': The Internet connection appears to be offline.., NSUnderlyingError=0x28991fc90 {Error Domain=NSURLErrorDomain Code=-1009 "The Internet connection appears to be offline." UserInfo={_kCFStreamErrorCodeKey=50, NSUnderlyingError=0x28991fa50 {Error Domain=kCFErrorDomainCFNetwork Code=-1009 "(null)" UserInfo={_NSURLErrorNWPathKey=satisfied (Path is satisfied), interface: pdp_ip0[lte], ipv4, ipv6, dns, expensive, _kCFStreamErrorCodeKey=50, _kCFStreamErrorDomainKey=1}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask .<9>, _NSURLErrorRelatedURLSessionTaskErrorKey=(     "LocalDataTask .<9>" ), NSLocalizedDescription=The Internet connection appears to be offline., NSErrorFailingURLStringKey=/mga/sps/oauth/oauth20/token, NSErrorFailingURLKey=****/mga/sps/oauth/oauth20/token, _kCFStreamErrorDomainKey=1}}}) I am not sure why I am getting this error. I am sure internet was available on my device at that time. Because I am getting success response for other registration tasks at that time (FYI, I request for access token using refresh token for the last 3 pushes I get i.e, 45th, 46th and 47th hours). Did someone run into this issue before. Please suggest me why I am getting this error and how to get rid of it. I am using iOS 13+ devices.
Posted
by
Post not yet marked as solved
0 Replies
236 Views
Hi everyone, I hope you're all doing well. I was wondering what is the most secure way to communicate with a login API to which I send credentials and get Json Web Token in case of a successful login ? Also, where should I store the JWT while the app is running ? I red in the documentation that "ATS requires that HTTP connections use HTTPS", so I thought that using URLSession is a good and secure solution. I'm quite new to SwiftUI and trying to learn what is the most secure way to communicate sensitive data to web API. Thanks in advance for your answers
Posted
by
Post not yet marked as solved
0 Replies
264 Views
hi so i am writing a networkManager class for downloading huge files from internet (more than 1.5GB) i am using URLSessionDownloadTask to do so but when user terminate the app urlsession didcompletewitherror calls before app termination and when app relunches it wont call again so i dont have access to resume data but i can confirm from folders than multiple data is availbile in tmp folder named CFD... what should i do ? how can i access resume data after app relunch let resumeData = (err as NSError).userInfo[NSURLSessionDownloadTaskResumeData] as Data i use this code to get resume data just before app termination . can i simply try to write this data to file in that little time before app termination?
Post not yet marked as solved
0 Replies
346 Views
In a UIKit context, has anyone had experience/success in using async/await to synchronize a modal dialog with other logic? I've tried it a bit without success. I.e, given a presented dialog, I want to capture data in the dialog, then use the results in a simple, linear fashion. (Something that looks like "Present the dialog, wait for results, use results" -- all inline without closures.) It seems to me that async/await with @MainActor ought to make that possible, but I haven't yet figured out how. I'd really like to see a real-world example.  Can you help?
Posted
by
Post not yet marked as solved
2 Replies
321 Views
Hello, I would like to create an app, which helps people to learn a language. The app content I would like to change using text files. As beginner in SWIFT programming I would need a hint how to pass new content in my app. I thought to use text files, placed on a web site. If the text file is updated, the app should get the newest content automatically. Does this make sense? What would be the best solution to achieve this target? Is there any helpful video in the "Developer" app or somewhere else? Thanks a lot.
Posted
by
Post not yet marked as solved
1 Replies
683 Views
Hi there, We need help with one issue. Sometimes our post API request are having the following error. I checked the server logs and seems everything okay in Apache and PHP logs. Seems something wrong with out almofire libraray Here is the error that we are having [Result]: failure(Alamofire.AFError.sessionTaskFailed(error: Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={_kCFStreamErrorCodeKey=-4, NSUnderlyingError=0x28139c840 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={NSErrorPeerAddressKey=<CFData 0x297c79400 [0x1ebb61860]>{length = 16, capacity = 16, bytes = 0x100201bb4834ca170000000000000000}, _kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask .<264>, _NSURLErrorRelatedURLSessionTaskErrorKey=( "LocalUploadTask .<264>" ), NSLocalizedDescription=The network connection was lost.,
Posted
by
Post not yet marked as solved
4 Replies
880 Views
Hi All, I wanted to perform the upload task in the background using a URLSessionConfiguration background session and after that, once the upload is done, I have to send the status API call to the server again. I have implemented the URLSession with background configuration and it is working fine and uploaded the file in the background or suspend state and invoke the app in the background with delegate. After uploading the file, I'm sending the status call to the server but it is not working and looks like the app is invoked for a few seconds and again went to the suspend state. Please suggest, how will I send status calls after the app invokes in the background for upload completion. Thanks in advance.
Posted
by
Post not yet marked as solved
2 Replies
898 Views
How can we call async functions in did set blocks? This code will trigger a compilation error: 'didSet' accessor cannot have specifier 'async' @Published var lastLocation: CLLocation? { didSet async { await pinPosition() } }
Posted
by