swift URLRequest调试扩展

URLRequestDebug
import Foundation
import os

extension URLRequest {
    
    func logDebugDescription() {
        guard let headerFields = allHTTPHeaderFields else {
            os_log("Unable to log info for request", log: Log.networking, type: .error)
            return
        }
        
        let methodDescription = "\(httpMethod ?? "") \(self)"
        if let body = httpBody {
            let bodyString = String(decoding: body, as: UTF8.self)
            os_log("METHOD: \n %s\nHEADERS: \n %s\nBODY: \n %s",
                   log: Log.networking,
                   type: .debug,
                   methodDescription,
                   headerFields.description,
                   bodyString)
        } else {
            os_log("METHOD: \n %s \nHEADERS: \n %s", log: Log.networking, type: .debug, methodDescription, headerFields.description)
        }
    }
    
}

swift 字符串链接扩展

string-link-extension
import Foundation

extension NSMutableAttributedString {
    
    public func setAsLink(textToFind: String, stringURL: String) -> Bool {
        let foundRange = mutableString.range(of: textToFind)
        
        if foundRange.location != NSNotFound {
            addAttribute(.link, value: stringURL, range: foundRange)
            return true
        }
        
        return false
    }
    
}

swift 要求兑换Alamofire

request-convertible
import Foundation
import Alamofire
import SwiftyJSON

enum SomeRequestConvertible: URLRequestConvertible {
    
    enum Constants {
        static let BaseUrlPath = "https://apilink.com"
    }
    
    enum RequestError: Error {
        case noAuthorizationToken
    }
    
    case createIdentity(IdentityObject)
    case uploadImageWithId(String)
    
    var method: HTTPMethod {
        switch self {
        case .createIdentity:
            return .post
        case .registerFace:
            return .post
    }
    
    var path: String {
        switch self {
        case .createIdentity:
            return "/api/v1/person"
        case .uploadImageWithId(let identifier):
            return "/api/v1/person/\(identifier)/image"
        }
    }
    
    var parameters: [String : Any]? {
        switch self {
        default:
            return nil
        }
    }
    
    public func asURLRequest() throws -> URLRequest {
        let url = try Constants.BaseUrlPath.asURL()
        
        var request = URLRequest(url: url.appendingPathComponent(path))
        request.httpMethod = method.rawValue
        
        guard let authToken = AuthorizationManager.shared.tokenResponse?.access_token else {
            throw RequestError.noAuthorizationToken
        }
        
        request.addValue("Bearer \(authToken)", forHTTPHeaderField: "Authorization")
        
        
        //Setup headers
        switch self {
        case .registerFace(_):
            request.addValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
        default:
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.setValue("application/json", forHTTPHeaderField: "Accept")
        }
        
        //Setup parameters or body
        switch self {
        case .createIdentity(let identity):
            let jsonObject = [ "firstName" : identity.firstName,
                               "lastName" : identity.lastName]
            let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
            request.httpBody = jsonData
        default:
            if let parameters = parameters {
                request = try URLEncoding.default.encode(request, with: parameters)
            }
        }
        
        request.logDebugDescription()

        return request
    }
    
}

swift 记录系统示例

log-system
import Foundation
import os

private let subsystem = "com.mycompany.myproject"

struct Log {
    
    static let authorization = OSLog(subsystem: subsystem, category: "authorization")
    static let networking = OSLog(subsystem: subsystem, category: "network")
    static let storage = OSLog(subsystem: subsystem, category: "storage")
    static let ui = OSLog(subsystem: subsystem, category: "ui")
    
    static let tests = OSLog(subsystem: subsystem, category: "tests")

}

//How to use
os_log("Token refreshed successfully. Received token: \n %s", log: Log.authorization, type: .debug, accessToken)
os_log("Unable to log info for request", log: Log.network, type: .error)
os_log("Root scene transition completed", log: Log.ui, type: .info)

swift 突出显示文本中的链接

highlight-links-in-text
class ViewController: UIViewController, UITextViewDelegate {
    @IBOutlet var textView: UITextView!

    override func viewDidLoad() {
        let attributedString = NSMutableAttributedString(string: "Want to learn iOS? You should visit the best source of free iOS tutorials!")
        attributedString.addAttribute(.link, value: "https://www.hackingwithswift.com", range: NSRange(location: 19, length: 55))

        textView.attributedText = attributedString
    }

    func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool {
        UIApplication.shared.open(URL)
        return false
    }
}

swift HTTP体的JSON

json-for-httpbody
let jsonDict = [ "firstName" : names.firstName,
                 "lastName" : names.lastName]
let jsonData = try JSONSerialization.data(withJSONObject: jsonDict, options: .prettyPrinted)
request.httpBody = jsonData //URLRequest

swift 斯威夫特单身人士

swift-singleton
class DeviceInfoProvider {
    static let shared = DeviceInfoProvider()
    
    private init() {}
}

swift Swift信号量

swift-semaphore
let semaphore = DispatchSemaphore(value: 0)
semaphore.signal()
semaphore.wait()

swift Alamofire图片上传

image-uploading
let image = UIImage.init(named: "myImage")
let imgData = UIImageJPEGRepresentation(image!, 0.2)!

let parameters = ["name": rname] //Optional for extra parameter

Alamofire.upload(multipartFormData: { multipartFormData in
        multipartFormData.append(imgData, withName: "fileset",fileName: "file.jpg", mimeType: "image/jpg")
        for (key, value) in parameters {
                multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            } //Optional for extra parameters
    },
to:"mysite/upload.php")
{ (result) in
    switch result {
    case .success(let upload, _, _):

        upload.uploadProgress(closure: { (progress) in
            print("Upload Progress: \(progress.fractionCompleted)")
        })

        upload.responseJSON { response in
             print(response.result.value)  
        }

    case .failure(let encodingError):
        print(encodingError)  
    }
}

swift 录音服务

允许录制和播放音频文件。 <br/>更多信息:<br/> https://www.hackingwithswift.com/example-code/media/how-to-record-audio-using-avaudiorecorder <br/> https://www.hackingwithswift。 COM /例子代码/媒体/如何对播放的声音 - 使用 - avaudioplayer

record-audio
import Foundation
import AVFoundation

class AudioRecordingService: NSObject {
    
    private let recordingSession = AVAudioSession.sharedInstance()
    private(set) var audioRecorder: AVAudioRecorder!
    private(set) var audioPlayer: AVAudioPlayer?
    
    //MARK: - Public methods
    
    public func startRecordingProcess() {
        print("Audio recording has started.")
        
        do {
            try recordingSession.setCategory(.playAndRecord, mode: .default)
            try recordingSession.setActive(true)
            recordingSession.requestRecordPermission { [unowned self] allowed in
                DispatchQueue.main.async {
                    if allowed {
                        self.record()
                    } else {
                        print("Recording is restricted by user.")
                    }
                }
            }
        } catch {
            print("Error while requesting permissions: \(error.localizedDescription).")
        }
    }
    
    public func stopRecording() {
        audioRecorder.stop()
        audioRecorder = nil
        print("Audio record finished.")
    }
    
    public func playRecord() {
        let url = getDocumentsDirectory().appendingPathComponent("voiceRecord.aac")
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            audioPlayer?.play()
        } catch {
            print("Error: can't play audio. \(error.localizedDescription).")
        }
    }
    
    //MARK: - Private methods
    
    private func record() {
        let audioFilePath = getDocumentsDirectory().appendingPathComponent("voiceRecord.aac")
        print("File saved at: \(audioFilePath.absoluteString)")
        
        let settings = [ AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
                         AVSampleRateKey: 12000,
                         AVNumberOfChannelsKey: 1,
                         AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue ]
        
        do {
            audioRecorder = try AVAudioRecorder(url: audioFilePath, settings: settings)
            audioRecorder.delegate = self
            audioRecorder.record()
        } catch {
            print("Error! \(error.localizedDescription)")
        }
    }
    
    private func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }
    
}

extension AudioRecordingService: AVAudioRecorderDelegate {
    //TODO: research
//    func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
//        stopRecording()
//    }
}