Alamofire 5 in Swift UI


Alamofire is Swift-based HTTP networking library for iOS and macOS. it provides is easy to use, chainable request/ response methods, JSON parameter and response serialization, authentication, and many other features.

import Alamofire 5 in swift UI with Cocoapods :

  • Open terminal and go to your project folder
  • Pod init
  • vim podfile and embed 

# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'AlamofireWithSwiftUI' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for AlamofireWithSwiftUI
  pod 'Alamofire', '~> 5.2'
  target 'AlamofireWithSwiftUITests' do
    inherit! :search_paths
    # Pods for testing
  end

  target 'AlamofireWithSwiftUIUITests' do
    # Pods for testing
  end

end

    • pod install

    Create new model and implementation Identifiable, identifiable is class of type whose instance hold the value of an entity with stable identity.

    struct JokesData: Identifiable {
        public var id: Int
        public var joke: String
    }

      Create new Class ObservableObject to get data with Alamofire 5 :

      import SwiftUI
      import Alamofire

      class JokesDataApi: ObservableObject {
          @Published var jokes = [JokesData]()
          init() {
              getJokes()
          }
          func  getJokes(count: Int = 5) {
              let urlJokes = "http://api.icndb.com/jokes/random/\(count)"
              AF.request(urlJokes, method: .get, parameters: nil).responseJSON { response in switch response.result {
              case .success(_):
                  if let json = response.value {
                      if (json as? NSDictionary) != nil {
                          if let dictionaryArray = json as? Dictionary<String, AnyObject?> {
                              let jsonArray = dictionaryArray["value"]
                              if let jsonArray = jsonArray as? Array<Dictionary<String, AnyObject?>> {
                                  for i in 0..<jsonArray.count {
                                      let json = jsonArray[i]
                                      if let id = json["id"] as? Int, let jokeString = json["joke"] as? String {
                                          self.jokes.append(JokesData(id: id, joke: jokeString))
                                      }
                                  }
                              }
                          }
                      }
                  }
              case .failure(let error):
                  print("error -> : \(error.localizedDescription)")
                  }
              }
          }
      }


        Create new file and design you interface. At this time, we use a navigation view. where the navigation view has a trailing that we can use to add attributes. like "More" button which is used to add new jokes

        import SwiftUI

        struct JokesView: View {
            @ObservedObject var observed = JokesDataApi()
            var body: some View {
                NavigationView {
                    List(observed.jokes) { i in
                        HStack {
                            CircleImage(imageName: "icon_laughing", size: 50)
                            Text(i.joke).font(.system(size: 12))
                        }
                    }.navigationBarItems(trailing: Button(action: getJokes, label: { Text("More").bold().font(.system(size: 15)) }))
                    .navigationBarTitle("Jokes")
                }
            }
            func getJokes() {
                observed.getJokes(count: 1)
            }
        }

        struct JokesView_Previews: PreviewProvider {
            static var previews: some View {
                JokesView()
            }
        }

           
          Don't forget to Allow Arbitrary Loads in Info.plist



          Output :












            Alamofire 5 in Swift UI Alamofire 5 in Swift UI Reviewed by sdiik on January 18, 2021 Rating: 5

            No comments:

            Powered by Blogger.