用swift和API编写ios应用-随机用户

本文档详细介绍了如何使用Swift 4和iOS 11.2来创建一个应用程序,其中包括设置界面、添加BarbuttonItem、创建视图、添加图片和用户头像,以及最终整合TableViewController来显示随机用户信息。通过一步步的指导,读者将学习到如何实现应用的完整流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

版本:

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: "abcde@qq.com", 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.制作完成
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值