编辑代码

{
    "refresh_token": "25.b55fe1d287227ca97aab219bb249b8ab.315360000.1798284651 .282335-8574074"
    "expires in": 2592000,
    "scope":"public wise adapt",
    "session_ key": "9mzaDZXu3dENdEZQurfgOVz8s1gSgvvOAUebNFzyzcp05EnbxbF+ h£G9DQkpUVQdh4p6HbQcAiz5RmuBAjalJJGgIdJI",
    "access_ token": "24.6c5e1 £f107f0e8bcef8c45a3424a0e78 .2592000.1485516651.
282335-8574074",
"session secret": "Afac94a3489fe9fca7c3221cbf7525ff"

}
{
    "error": "invalid client",
    "error_description": "unknown client id"
    }
    # encoding: utf-8
    import requests


#Client id 为官网获取的 AK, client secret 为官网获取的 SK
host = 'lhttps: //aip.baidubce.com/ oauth/2.0/ token?grant_type=client_
credentials&client_id= 【官网获取的 AK】 &client secret= 【官网获取的 SK】'
response = requests.get(host)
if response
print(response.json())
import requests 
import base64
'''
车型识别
''''
request_url = "https://aip.baidubce.com/rest/2.0/image-classiEy/v1/
car"
# 二进制方式打开图片文件
£ = open([本地文件],'rBr')
img = base64.b64encode (f. read ())


params = "{"image" :img, "top_num":5}
access_token = "[调用签权接口获取的 token],
request_url = request url + "?access token=" + access_token
headers = {'content-type!': 'application/ x-www-form-ur1encoded'}
response = requests.post (request_url, data-params, headers-headers)
if response:
print (response.json ())
返回的 JSON 数据:
{
    "log_id”: 4086212218842203806,
    "location result": {
        "width": 447,
        "top": 226,
        "height": 209,
        "left": 188
},
"result":[
    "baike info": {
        "baike url: "http://baike.baidu.com/iten/E5%B8%83%5%82%A08E8BFAAchi
ron/20419512",
rdescription":〞布加迪 Chiron 是法国跑车品牌布加迪出品的豪华超跑车。配置四涡轮
增压发动机,420 公里每小时,有23种颜色的选择。售价高达 260万美元。“
}, 
"score": 0.98793351650238,
"name”:" 布加迫 Chiron",
"year":"无年份信息"
},
{
    "score": 0.0021970034576952,
    "name”:” 奥迫RS5",
    "year": "2011-2017"
},
{
"score": 0.0021096928976476

*2
{
    "Name": "Chen Zhifeng",
    "Profession": "Teacher",
    "Age": 46,
    "Email": "13402506301@163.con",
    "Eriends" : InZhang San", "Li si"]

    }
    {
        "TeamName":"i0S-Orange-Team",
        "Teacher": "Chen Zhifeng",
        "Students": [
            { "Name": "Zhang Bo","Hometown": "Xuzhou"'},
            {"Name": " Chang Wenxiang ", "Hometown": "Yancheng"),
            {"Name" :" Hu Yinting". "Hometown": "Suzhou"}
            ]
            }
            {
                "coord": ("lon": -0.13, "lat": 51.51},
                "weather": ("id": 300, "main": "Drizzle", "description": "light
intensity drizzle", "icon": "09d"} ],
"base":"stations"
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp min":279.15,
"temp_max":281.15
}, 
"visibility": 10000,
"wind": ("speed": 4.1, "deg": 801},
"clouds": ("all": 90},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise" :1485762037
"sunset": 1485794875
}, 
"id": 2643743,
"name": "London",
"cod":200

}

*3
{
    "Name": "Chen Zhifeng",
    "Profession": "Teacher",
    "Age": 46,
    "Email": "13402506301@163.con",
    "Eriends" : InZhang San", "Li si"]

    }
    {
        "TeamName":"i0S-Orange-Team",
        "Teacher": "Chen Zhifeng",
        "Students": [
            { "Name": "Zhang Bo","Hometown": "Xuzhou"'},
            {"Name": " Chang Wenxiang ", "Hometown": "Yancheng"),
            {"Name" :" Hu Yinting". "Hometown": "Suzhou"}
            ]
            }
            {
                "coord": ("lon": -0.13, "lat": 51.51},
                "weather": ("id": 300, "main": "Drizzle", "description": "light
intensity drizzle", "icon": "09d"} ],
"base":"stations"
"main": {
"temp": 280.32,
"pressure": 1012,
"humidity": 81,
"temp min":279.15,
"temp_max":281.15
}, 
"visibility": 10000,
"wind": ("speed": 4.1, "deg": 801},
"clouds": ("all": 90},
"dt": 1485789600,
"sys": {
"type": 1,
"id": 5091,
"message": 0.0103,
"country": "GB",
"sunrise" :1485762037
"sunset": 1485794875
}, 
"id": 2643743,
"name": "London",
"cod":200

}

*4
Func sessionGetData () {
    //创建 URI 对象
    let urlstring = "http: //www.tuling123.com/"
    let url = uRL (string: urlstring)
    //创建请求对象
    let request = URLRequest (url: url!)


    let session = URISession . shared
    iet datarask = session.dataTask (with: request,
    completionHandler: ( (data, response, error) -> Void in
    if error != nilf{
        print (error.debugDescription)
        }else{
            let str = String (data: data!, encoding:
String. Encoding.utf8)
print (str!)

        }) as URLSessionTask
        //使用 resume 方法启动任务
        dataTask. resume ( )
}
func sessionDownloadImage () {
    //下载地址
    let url = URL (string: "http: / /hangge.com/blog/ images/logo.png")
    //请求
    let request = ULRequest (url: url!)


    let session = URLSession.shared
    //下载任务
    let downloadTask = session. downloadTask (with: request,
completionHandler: {
    (location : URL?, response : URLResponse?, error:ErrOr?)
    -> Void in
    //输出下载文件原来的存放目录
    print ("location : 1 (string (describing : 1ocation))")
    //1ocation 位置转换
    let locationPath = location?.path

    //获取当前时间
    let now = NsDate ()
    //当前时间的时问戳
    let timeInterval: TimeInterval = now. timeIntervalSince1970
    let timestamp = String (timeInterval)
    //拷贝到用户目录
    let documents: String = NSHomeDirectory () + "/Documents/\(timeStamp).png"
    //创建文件管理器
    let fileManager = FileManager. default
    try! fileManager moveItem (atPath: locationPath!, toPath:documents)
    print ("new location: 1 (documents)")

} )
//使用resume 方法启动任务
downloadTask.resume ()
}
<?php
/** php 接收流文件
* @param String $file 接收后保存的文件名
* @return boolean
* /
function receiveStreamFile ($receiverile) {
    $streampata = isset (SCLOBALST 'HTTP RAW POST_ DATA'])? SGLOBATS L'HTTP_RAW POST DATA'] : '';

if (empty ($streamData)) {
    $streamData = file_get_contents ('php://input");
    }

    if ($streamData!='') {
        $ret = file _put_contents ($receiveFile, $streamData, true);
        }else {
            $ret = false;

            }

            rqeeturn $ret;

        }
// 定义服务器存储路径和文件名
$receiverile = $_SERVERL" DOCUMENI ROOT"J ."/ uploadFiles / swift . png";
echo $receiveFile;
$ret = receiveStreamFile ($receiveFile) ;
echo json_ encode (array ('success ' => (bool) sret))i

?>
func sessionUploadPhp () {
//上传地址
let uri = URL(string: "http://localhost/uploadSwift.php")
//1.创建会话对象
let session = URLSession.shared
//请求
var request - URLecuest (url: uri!, cachePolicy: •reloadIgnoringCacheData)
request.httpMethod = "POST"
//上传数据流
iet tileImage = Bundle. main.path (forResource : "beel ", ofType: "png")
iet ingData = try! Data (contentsOf: URL (til eURIWi thPath: tileImage !))


let uploadIask = session.uploadTask (with: request as URLRequest, from:imaData) {
    (data: Data?, response: URLResponse?, error:Error?) -> Void in
    //上传完毕后
    if error != nill
    print (error!)
}else {
    let str = string (data: data!, encoding: string .Encoding .utf8)
    print"上传完毕:\(String (describing:stz))")
    }
    }
//使用resume 方法启动任务
uploadTask.resume ()
}

*5
import UIKit 
import Foundation


let API Key = "EIpAlhdD715152EsiNgpUOF_"
let Secret Key = "P8EzWg4agjDOxABmKVBYSNyZ1YzGFqb_"


let token_ host = "https: //aip.baidubce.com/oauth/2.0/token?grant_type=client_ credentials&client id=\(API Key) &client secret =\ (Secret_Key)"


var access token = ""
var expires in: Int32 = 0


if let url = URL (string: token host) {
    URLSession. shared. dataTask (with: url) (data, response, error) in
    if error != nil {
        print ("network error")
    }
    else {
        if let json = try? JSONSerialization.jsonObject (with: data!,options: allowFragments) as?[String:Any] {
            access token = json ["access token"] as! String
            expires in = ison["expires_in"las! Int32
            print ("--------accesstoken------")
            printaccess token)
            print ("--------expires_time------")
            print (expires_in)

            }
            }
            }.resume()
            }
            else {
                print("url error")

            }
            //以文本或者二进制方式读入源程序文件的 Ioader
            public struct Loader
            static func readTxt (file url:URI) ->String? {
                do {
                    let source = try String (contentsOf: ur1)
                    return source

}
catch {
    return nil
    }
    }
    static func readBin (file url:URL) 一> Data? {
        do {
            let data = try Data (contentsOf: url)
            return data

}
catch {
    return nil
    }
    }
    }
    //Resources 中的文件,并把路径转化为 URL
    let path = Bundle. main.path (forResource: "grcar. jpg", ofType: nil)
    let url = URL (fileURLWithPath: path!)


    let data = Loader.readBin (file: url)


    if(data == nil) {
        print ("File failed to load")
    }

    let data base64 str = data? .base64EncodedString()
    let data base64 = data?.base64EncodedData ( )


    access token="24.2ec96a68£742842900£07869929413ae.2592000.1598921312.282335-21737249"
    let carType host ="https://aip.baidubce.com/rest/2.0/image-classify/v1/car" + "?access_token=" + "\(access_token)"

    if let url = URL(string: carType_host)
    var request = URLRequest (url: ur1)
    request. setValue ("application/×-www-form-urlencoded", forHTTPHeaderField:"Content-Type")
    request.httpMethod = "POST"


    let cs = NSCharacterSet (charactersIn: "/=+%") inverted
    let image_urlEncode = data base64 str!addingPercentEncoding (withAllowedCharacters: cs)
    let postString = "image=\(image urlEncode!) &top num=5&baike_num-1"

    request.httpBody = postString.data (using:utf8)

    URLSession.shared.dataTask(with: request) { (data,response, error) in
    if error != nil {
        print ("error")

}
else {
    let rs = String (data: data!, encoding: String. Encoding.utf8)
    print(rs!)
    }
    }
.resume ()
}
{
    “log id" : 4368540366187197442,
    "location result:
{
"width":386.4585876464844,
"top": 81.3405532836914,
"height": 183.9795532226562,
"left": 58.03330230712891
}, 
"result":

[
    {
        "score":0.9767324924468994,
        "year": "2014-2017",
        "baike_info":
        {
            "baike url": i/item/8E5gA5%87%87%91%9EE5/475143",
            "image arl":
            "/pic/5882b2b7a0a20cf47a91d7777c094b36acaf9910",
            "description":
            "2014 款奇瑞巴5 是国内科技家桥的引领者,带领消费者悦享领先科技。"
            },
"name""奇瑞E5"
        },
        {
"score : 0.007103727199137211,
"name":"奇瑞旗云",
"year": "2010-2013"
        },
        {
"score":0.003686367534101009,
"name":"奇瑞艾瑞泽 7",
"year": "2016-2017"
},
{
"score": 0.001757977530360222,
"name":“ 奇瑞53”,
"year": "2015-2017"
},
{
"score": 0.001047104829922318,
"name ":“ 奇瑞A5",
"year": "2015"
}
],
"color result" " 黒色"


}
//
// ViewController.swift
// CameraUsge
//
// Created by Zhifeng Chen on 2020/8/2.
// Copyright • 2020 Zhifeng Chen. All rights reserved.
//


import UIKit


class ViewController: UIViewcontroller , UINavigationControllerDelegate,UITmagePickerControllerDelegate{
    //设置因像显示用的outlet,就是变量 car ImageView
    @IBOutlet weak var carImageView: UIImageView!
    //设置 Action,由相册按钮事件触发
    @IBAction func onLibrary (_sender: UIButton) {
        //设置相册拍照的控制器
        let vc = UIImagePickerController ()
        //设置为相册
        vC. sourceType = .photoLibrary
        vc.allowsEditing = true
        vc.delegate = self
        present (vc, animated: true)
     } 
     //设置Action,由拍照按钮事件触发
     @IBAction func oncamera( sender: UIButton) {
         let vc = UlImagePickerController ()
         //设置为摄像头
         vc. sourceType = .camera
         vc.allowsEditing = true
         vc. delegate = self
         present (vC, animated: true)
     }
         //相價荻取圏片需要凋用的 Delegate
         func imagePickerController|_ picker: UIImagePickerController didFinishPickingMediawithInfo info: (UI ImagePickerController.InfoKey: Any))
         picker. dismiss (animated: true)
         guard let image = infol.editedImage\ as? UI Image else {
             return
          }
          // 将相册图片显示在 carImageview 中
          carImageView.image = image

}
}
//
// ViewController.swift
// CameraUsage
// 
// Created by Zhifeng Chen on 2020/8/2.
// Copyright © 2020 Zhifeng Chen. All rights reserved.
//


import UIKit


class viewcontroller: UIViewcontroller , UINavigationcontrol1erDelegate,UIInagePickercontrollerDelegatet{
    //设置图像显示用的outlet,就是变量 car Imageview
    @ IBoutlet veak var carImageview : UIImageview!
    //显示识别出来的车辆名称型号
    @IBOutlet weak var carDetails: UILabel !
    //设置 Action,由相册按钮事件触发
    @IBAction func onlibrary ( sender: UIButton) {
        //设置相册拍照的控制器
        let ve = UIImagePickercontroller ()
        //设置为相册
        vC.sourceType = .photoLibrary
        vc.allowsEditing = true
        vc.delegate = self
        present (vc, animated: true)
}
// 设置Action,由拍照按钮事件触发
@IBAction func onCamera ( sender: UIButton) {
    let vc = UIInagePickerController ()
    //设置为摄像头
    vc. sourceType = .camera
    vc.allowsEditing = true
    vc.delegate = self
    present (vc, animated: true)
}
//相册英取图片需要调用的 Delegate
func imagePickerController ( picker: UIImagePickerController,didFinishPickingMediaWithInfo info: (UIImagePickerController. InfoKey : Any]) {
    picker.dismiss (animated: true)
    guard let image = info [.editedImage] as? UIImage else {
        return
    }
//将相册图片显示在 carImageview 中
carImageView.image = image
//获得百度AI平台access_token
Let access token = get baidu_ token ()
if access_token == "" {
    return
}
else {
    //1从百度A工 获得车型信息
    get_car_ type (access token: access_token)
}
}


//传入有效的access_ token,上传图片,荻得车型信息
func get car type (access token: String) {
    //获取显示的图片,,并保存为jpg格式
    let image = carImageView. image
    //let data = UIImagePNGRepresentation (image)
    guard let data = image!. jpegData (compressionQuality: 0.5) else (
        return
}
//将图片进行 base64 编码
let data base64 str = data.base64Encodedstring ()
//准备好获取车型的AB工 的URI, 的字符串
let carType host = "https: //aip.baidubce.com/ rest /2.0/ image-classify/v1/car" + "?access token=" + "' (access token) "
//从字符串转换为 URL
if let url = URI (string: carrype host) {
    //从 URI 生成 URIRequest
    var reguest = URLReguest (url: url)
    //设置 ETP HEADER 中的 content-Type 为 application/x-www-form-urlencoded
    request. setValue ("application/x-www-form-urlencoded", fortITPHeaderField:"content-Type")
    //设置为 POSI 方法
    request.httpMethod = "POST"
    //将图片文件进行 urlencode 转码
    let cs = NSCharacterset (charactersIn: "/=+8").inverted
    let image urlEncode = data base64 str .addingPercentEncoding  (withAllovedCharacters:cs)
    //合并三个参数为一个字符串
    let poststring = "image=1 (image_ ur1Encode !) atop num=5abaike num-1"
    //将字符串转为UTF8 类的数据
    request.httpBody = postString.data (using: .utf8)
    //URLSession 调用
    URISession. shared.dataTask (with: request) | (data, response,error) in
    if error != nil {
        print("error")
    }
    else {
        if let json = try? JSONSerialization. jsonObject (with:data!, options: .allowFragments) as? [String : Any] (
            let result = son ["result") as! Array<Dictionary<String, Any>>
            let name = result (0] ("name"] as! String
            var description ="非车类”
            if name != n 非车类"(
                let baike info = result (0] ("baike info"] as!Dictionary<String, String>
                if let details = baike info["description"] {
                    description = details

}
else {
    desoription = "百度百科无此车资料"
}
    }
    //转入主线程
    DispatchQueue.main.async {
        self .carDetails.text = description
        self.carName.text = name
    }
}
}
}
•resume ( )
}
}

//以信号量方式等待网络结果返回access_token,如果没有成功,则返回"”
func get baidu_ token () -›String {
    let API_Key = "EIpAlhdD7i5152EsiNgpU0F1"
    let Secret_Key = "p8EZWg4ag]DOxABmKvBYSNyZ1ŸzGFqbm"
    let token host = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client credentials&client id=\(API Key) §client secret=\ (Secret _Key) "

var access token = ""
//设置信号量
let semaphore: DispatchSemaphore = DispatchSemaphore (value: 0)

if let url = URL (string: token host) {

URI.Session. shared. datalask (with: url) | (data, response, error) in iferror!= nil {
    print ("network error")
}
else {
    if let json = try? JSONSerialization. jsonObject (with:data!, options: allowFragments) as? [String : Any] {
        access_token = json ["access token"] as! String
    }
}
//发出信号量
semaphore.signal ()
}
.resume ()
}
else {
    print ("url error")
}
//等待信号量
semaphore.wait ()
return access token
}
}