用swift和API編寫ios應用-隨機用戶

版本:

swift 4,ios 11.2

1.視圖畫面
這裏寫圖片描述
2.添加BarButtonItem
這裏寫圖片描述
3.配對一個子類
這裏寫圖片描述
4.添加一個視圖
這裏寫圖片描述
5.添加圖片
這裏寫圖片描述
6.添加用戶圖片
這裏寫圖片描述
7.選擇圖片
這裏寫圖片描述
8.添加用戶圖標
這裏寫圖片描述
9.添加ContainerView
這裏寫圖片描述
10.添加TableViewController
這裏寫圖片描述
11.轉換成cell
這裏寫圖片描述
12.調整行數
這裏寫圖片描述
13.添加信息標籤
這裏寫圖片描述
14.調整背景和文字顏色
這裏寫圖片描述
15.編寫代碼
ViewController.swift

//  ViewController.swift
//  RandomUser
//
//  Created by lin on 2018/3/29.
//  Copyright © 2018年 lin. All rights reserved.
//

import UIKit
import AudioToolbox

struct User{
    var name:String?
    var email:String?
    var number:String?
    var image:String?
}

struct AllData:Decodable{
    var results: [SingleData]?
}

struct SingleData:Decodable {
    var name:Name?
    var email:String?
    var phone:String?
    var picture:Picture?
}

struct Name:Decodable {
    var first:String?
    var last:String?
}

struct Picture:Decodable {
    var large:String?
}

class ViewController: UIViewController {

    @IBOutlet weak var userImage: UIImageView!
    @IBOutlet weak var userName: UILabel!
    var infoTableViewController:InfoTableViewController?
    let apiAddress = "https://randomuser.me/api/"
    var urlSession = URLSession(configuration: .default)
    var isDownloading = false

    @IBAction func makeNewUser(_ sender: UIBarButtonItem) {
        if isDownloading == false{
            downloadInfo(withAddress: apiAddress)
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        //change navigation bar color
        navigationController?.navigationBar.barTintColor = UIColor(red: 0.67, green: 0.2, blue: 0.157, alpha: 1)
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]   //改變標題文字顏色爲白色

//        let aUser = User(name: "lin", email: "[email protected]", number: "666-666", image: "http://picture.me")

//        settingInfo(user: aUser)
        downloadInfo(withAddress: apiAddress)
    }

    func downloadInfo(withAddress webAddress:String){
        if let url = URL(string: webAddress){
            let task = urlSession.dataTask(with: url, completionHandler: {
                (data,response,error) in
                if error != nil{
                    let errorCode = (error! as NSError).code
                    if errorCode == -1009{
                        DispatchQueue.main.async {
                            self.popAlert(withTitle: "No internet connection!")
                        }
                    }else{
                        DispatchQueue.main.async {
                            self.popAlert(withTitle: "Sorry")
                        }
                    }
                    self.isDownloading = false
                    return
                }
                if let loadedData = data{
                    do{
//                        let json = try JSONSerialization.jsonObject(with: loadedData, options: [])
//                        DispatchQueue.main.async {
//                            self.parseJson(json: json)
//                        }

                        let okData = try JSONDecoder().decode(AllData.self, from: loadedData)
                        let firstName = okData.results?[0].name?.first
                        let lastName = okData.results?[0].name?.last
                        let fullName:String? = {
//                            guard let okFirstName = firstName else {return nil}
//                            guard let okLastName = lastName else {return nil}
                            guard let okFirstName = firstName, let okLastName = lastName else {return nil}
                            return okFirstName + " " + okLastName
                        }()
                        let email = okData.results?[0].email
                        let phone = okData.results?[0].phone
                        let picture = okData.results?[0].picture?.large
                        let aUser = User(name: fullName, email: email, number: phone, image: picture)
                        DispatchQueue.main.async {
                            self.settingInfo(user: aUser)
                        }


                    }catch{
                        DispatchQueue.main.async {
                            self.popAlert(withTitle: "Sorry")
                        }
                        self.isDownloading = false
                    }
                }else{
                    self.isDownloading = false
                }
            })
            task.resume()
            isDownloading = true
        }

    }

    func parseJson(json:Any?){
        if let okJson = json as? [String:Any]{
            if let infoArray = okJson["results"] as? [[String:Any]]{
               let infoDictionary = infoArray[0]
               let loadedName = userFullName(nameDictionary: infoDictionary["name"])
               let loadedEmail = infoDictionary["email"] as? String
               let loadedPhone = infoDictionary["phone"] as? String
               let imageDictionary = infoDictionary["picture"] as? [String:String]
               let loadedImageAddress = imageDictionary?["large"]
               let loadedUser = User(name: loadedName, email: loadedEmail, number: loadedPhone, image: loadedImageAddress)
                settingInfo(user: loadedUser)
            }
        }
    }

    func userFullName(nameDictionary: Any?) -> String?{
        if let okDictionary = nameDictionary as? [String:String]{
            let firstName = okDictionary["first"] ?? ""
            let lastName = okDictionary["last"] ?? ""
            return firstName + " " + lastName
        }else{
            return nil
        }
    }

    func popAlert(withTitle title:String){
        let alert  = UIAlertController(title: title, message: "Please try again later", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        present(alert, animated: true, completion: nil)
    }

    func settingInfo(user:User){
        userName.text = user.name
        infoTableViewController?.phoneLabel.text = user.number
        infoTableViewController?.emailLabel.text = user.email
        if let imageAddress = user.image{
            if let imageURL = URL(string: imageAddress){
                let task = urlSession.downloadTask(with: imageURL, completionHandler: {
                    (url, response, error) in
                    if error != nil{
                        DispatchQueue.main.async {
                        self.popAlert(withTitle: "Sorry")
                        }
                        self.isDownloading = false
                        return
                    }
                    if let okURL = url{
                        do{
                            let downloadImage = UIImage(data: try Data(contentsOf: okURL))
                            DispatchQueue.main.async {
                                self.userImage.image = downloadImage
                                AudioServicesPlaySystemSound(1000)
                            }
                            self.isDownloading = false
                        }catch{
                            DispatchQueue.main.async {
                                self.popAlert(withTitle: "Sorry")
                            }
                            self.isDownloading = false
                        }

                    }else{
                        self.isDownloading = false
                    }
                })
                task.resume()
            }else{
                isDownloading = false
            }
        }else{
            isDownloading = false
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "moreinfo"{
           infoTableViewController = segue.destination as? InfoTableViewController
        }
    }

    override func viewDidAppear(_ animated: Bool) {   //畫面顯示到屏幕上以後纔會執行的方法
        super.viewDidAppear(animated)
        //make user image circle
        userImage.layer.cornerRadius = userImage.frame.size.width / 2    //將用戶方形圖片變成圓角圖片
        userImage.clipsToBounds = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

InfoTableViewController.swift

//  InfoTableViewController.swift
//  RandomUser
//
//  Created by lin on 2018/3/30.
//  Copyright © 2018年 lin. All rights reserved.
//

import UIKit

class InfoTableViewController: UITableViewController {
    @IBOutlet weak var phoneLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return 2
    }

WhiteNavigationController.swift

//  WhiteNavigationController.swift
//  RandomUser
//
//  Created by lin on 2018/3/29.
//  Copyright © 2018年 lin. All rights reserved.
//

import UIKit

class WhiteNavigationController: UINavigationController {

    override var preferredStatusBarStyle: UIStatusBarStyle{  //狀態欄改爲白色
        return .lightContent
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

16.製作完成
這裏寫圖片描述

發佈了28 篇原創文章 · 獲贊 10 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章