草庐IT

iOS | 技术点小计5

清無 2023-03-28 原文

WKWebView 设置Cookie

WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:@"document.cookie='X-Tag=gray;'" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[_webView.configuration.userContentController addUserScript:cookieScript];

NSURL *aURL = [NSURL URLWithString:url];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:aURL];
[_webView loadRequest:request];

Reachability

https://developer.apple.com/library/archive/samplecode/Reachability/Reachability.zip

麦克风权限检测

// 检测麦克风授权
- (void)checkAudioAuthorization {
    kWeak(weakSelf);
    void(^showUngrantedAlert)(void) = ^{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"麦克风未授权" message:@"请前往设置中开启,否则会导致通话没有声音。" preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"前往设置" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            NSURL *aURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if([UIApplication.sharedApplication canOpenURL:aURL]) {
                [UIApplication.sharedApplication openURL:aURL options:@{} completionHandler:nil];
            }
        }]];
        [weakSelf presentViewController:alert animated:YES completion:nil];
    };
    
    AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio];
    switch (status) {
        case AVAuthorizationStatusNotDetermined:
        {
            [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
                if(!granted) {
                    showUngrantedAlert();
                }
            }];
            break;
        }
        case AVAuthorizationStatusDenied:
        case AVAuthorizationStatusRestricted:
        {
            showUngrantedAlert();
            break;
        }
        default: break;
    }
    DDLogInfo(@"???? %s (%ld)", __func__, status);
}

OC 定义字符串枚举

typedef NSString *AVAudioSessionMode NS_STRING_ENUM;
OS_EXPORT AVAudioSessionMode const AVAudioSessionModeDefault;
OS_EXPORT AVAudioSessionMode const AVAudioSessionModeVoiceChat

Q: How do I fix "selector not recognized" runtime exceptions when trying to use category methods from a static library?

https://developer.apple.com/library/archive/qa/qa1490/_index.html#//apple_ref/doc/uid/DTS10004097

JS字符串中嵌入变量

console.log(`this is a test inner ${variable}`);

Jekyll

https://jekyllrb.com
http://jekyllthemes.org
sudo gem install -n /usr/local/bin jekyll
搭建博客
Themes

Swift hexString to UIColor

extension UIColor {
    static func hexColor(_ hexString: String, alpha: CGFloat = 1) -> UIColor? {
        var string = ""
        if hexString.lowercased().hasPrefix("0x") {
            string =  hexString.replacingOccurrences(of: "0x", with: "")
        } else if hexString.hasPrefix("#") {
            string = hexString.replacingOccurrences(of: "#", with: "")
        } else {
            string = hexString
        }

        if string.count == 3 {
            var str = ""
            string.forEach { str.append(String(repeating: String($0), count: 2)) }
            string = str
        }

        guard let hexValue = Int(string, radix: 16) else { return nil }

        let red = (hexValue >> 16) & 0xff
        let green = (hexValue >> 8) & 0xff
        let blue = hexValue & 0xff
        return .init(red: CGFloat(red)/255, green: CGFloat(green)/255, blue: CGFloat(blue)/255, alpha: 1)
    }
}

一种投机取巧快速实现自适应collection布局的方式

这种方式用到了私有API_rowAlignmentsOptionsDictionary,可能有不被过审的风险,仅供学习参考。

PS:垂直对齐好像现在还无法起作用,默认就是居中对齐的。

Left
Center
Right
class CollectionCell: UICollectionViewCell {
    @IBOutlet weak var textLb: UILabel!
}

extension String {
    func duplicated(times: Int, joined separator: String = "") -> Self {
        return (0..<times).map{ _ in self }.joined(separator: separator)
    }
}

class ViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        updateLayoutAlignment(.left)
    }
    
    @IBAction func changeAlignment(_ sender: UISegmentedControl) {
        guard let alignment = NSTextAlignment(rawValue: sender.selectedSegmentIndex) else {
            return
        }
        updateLayoutAlignment(alignment)
    }
    
    func updateLayoutAlignment(_ alignment: NSTextAlignment) {
        let layout = UICollectionViewFlowLayout()
        layout.estimatedItemSize = UICollectionViewFlowLayout.automaticSize
        var options = layout.value(forKey: "_rowAlignmentsOptionsDictionary") as? [String: Int]
        options?["UIFlowLayoutCommonRowHorizontalAlignmentKey"] = alignment.rawValue
        options?["UIFlowLayoutLastRowHorizontalAlignmentKey"] = alignment.rawValue
        layout.setValue(options, forKey: "_rowAlignmentsOptionsDictionary")
        
        CATransaction.disableActions()
        CATransaction.begin()
        collectionView.collectionViewLayout = layout
        CATransaction.commit()
    }
    
    lazy var items: [String] = Array(0...10).map{
        let times = Int(1 + arc4random() % 20)
        let enter = Int(1 + arc4random() % 10)
        return String($0)
            .duplicated(times: times, joined: ",")
            .duplicated(times: enter, joined: "\n")
    }
    
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CollectionCell", for: indexPath) as? CollectionCell else {
            return .init()
        }
        cell.textLb.text = items[indexPath.item]
        return cell
    }
    
    override func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
}

iOS13 手动切换夜间模式

  • Toggle view controller's view's key window's UserInterfaceStyle
guard 
  let currentStyle = view.window?.overrideUserInterfaceStyle 
else {
  return
}
// Or you can toggle `overrideUserInterfaceStyle` 
// for the whole app's key window:
/*
  UIApplication.shared.delegate?.window?.overrideUserInterfaceStyle = xxx
*/
let newStyle: UIUserInterfaceStyle = currentStyle == .light ? .dark : .light
view.window?.overrideUserInterfaceStyle = newStyle

// save the theme style settings to user defaults
UserDefaults.standard.setValue(newStyle.rawValue, forKey: "AppThemeStyle")
UserDefaults.standard.synchronize()

// @available(iOS 13.0, *)
// open var overrideUserInterfaceStyle: UIUserInterfaceStyle

Apply the user last saved theme settings when the app is initiated:

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    var window: UIWindow? {
        didSet{
            if let saved = UserDefaults.standard.value(forKey: "AppThemeStyle") as? Int,
               let style = UIUserInterfaceStyle(rawValue: saved) {
                window?.overrideUserInterfaceStyle = style
            }
        }
    }
}
  • Only toggle some specific one view controller's UserInterfaceStyle
let currentStyle = overrideUserInterfaceStyle
overrideUserInterfaceStyle =  currentStyle == .light ? .dark : .light

有关iOS | 技术点小计5的更多相关文章

  1. ruby - 如何验证 IO.copy_stream 是否成功 - 2

    这里有一个很好的答案解释了如何在Ruby中下载文件而不将其加载到内存中:https://stackoverflow.com/a/29743394/4852737require'open-uri'download=open('http://example.com/image.png')IO.copy_stream(download,'~/image.png')我如何验证下载文件的IO.copy_stream调用是否真的成功——这意味着下载的文件与我打算下载的文件完全相同,而不是下载一半的损坏文件?documentation说IO.copy_stream返回它复制的字节数,但是当我还没有下

  2. Ruby 文件 IO 定界符? - 2

    我正在尝试解析一个文本文件,该文件每行包含可变数量的单词和数字,如下所示:foo4.500bar3.001.33foobar如何读取由空格而不是换行符分隔的文件?有什么方法可以设置File("file.txt").foreach方法以使用空格而不是换行符作为分隔符? 最佳答案 接受的答案将slurp文件,这可能是大文本文件的问题。更好的解决方案是IO.foreach.它是惯用的,将按字符流式传输文件:File.foreach(filename,""){|string|putsstring}包含“thisisanexample”结果的

  3. Unity 热更新技术 | (三) Lua语言基本介绍及下载安装 - 2

    ?博客主页:https://xiaoy.blog.csdn.net?本文由呆呆敲代码的小Y原创,首发于CSDN??学习专栏推荐:Unity系统学习专栏?游戏制作专栏推荐:游戏制作?Unity实战100例专栏推荐:Unity实战100例教程?欢迎点赞?收藏⭐留言?如有错误敬请指正!?未来很长,值得我们全力奔赴更美好的生活✨------------------❤️分割线❤️-------------------------

  4. Get https://registry-1.docker.io/v2/: net/http: request canceled while waiting - 2

    1.错误信息:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:requestcanceledwhilewaitingforconnection(Client.Timeoutexceededwhileawaitingheaders)或者:Errorresponsefromdaemon:Gethttps://registry-1.docker.io/v2/:net/http:TLShandshaketimeout2.报错原因:docker使用的镜像网址默认为国外,下载容易超时,需要修改成国内镜像地址(首先阿里

  5. MIMO-OFDM无线通信技术及MATLAB实现(1)无线信道:传播和衰落 - 2

     MIMO技术的优缺点优点通过下面三个增益来总体概括:阵列增益。阵列增益是指由于接收机通过对接收信号的相干合并而活得的平均SNR的提高。在发射机不知道信道信息的情况下,MIMO系统可以获得的阵列增益与接收天线数成正比复用增益。在采用空间复用方案的MIMO系统中,可以获得复用增益,即信道容量成倍增加。信道容量的增加与min(Nt,Nr)成正比分集增益。在采用空间分集方案的MIMO系统中,可以获得分集增益,即可靠性性能的改善。分集增益用独立衰落支路数来描述,即分集指数。在使用了空时编码的MIMO系统中,由于接收天线或发射天线之间的间距较远,可认为它们各自的大尺度衰落是相互独立的,因此分布式MIMO

  6. ruby - 为什么不能使用类IO的实例方法noecho? - 2

    print"Enteryourpassword:"pass=STDIN.noecho(&:gets)puts"Yourpasswordis#{pass}!"输出:Enteryourpassword:input.rb:2:in`':undefinedmethod`noecho'for#>(NoMethodError) 最佳答案 一开始require'io/console'后来的Ruby1.9.3 关于ruby-为什么不能使用类IO的实例方法noecho?,我们在StackOverflow上

  7. ruby-on-rails - 用于门户的 Ruby 技术 - 2

    我刚刚看到whitehouse.gov正在使用drupal作为CMS和门户技术。drupal的优点之一似乎是很容易添加插件,而且编程最少,即重新发明轮子最少。这实际上正是Ruby-on-Rails的DRY理念。所以:drupal的缺点是什么?Rails或其他基于Ruby的技术有哪些不符合whitehouse.org(或其他CMS门户)门户技术的资格? 最佳答案 Whatarethedrawbacksofdrupal?对于Ruby和Rails,这确实是一个相当主观的问题。Drupal是一个可靠的内容管理选项,非常适合面向社区的站点。它

  8. iNFTnews | 周杰伦18年前未发布的作品Demo,藏在了区块链技术里 - 2

    当音乐碰上区块链技术,会擦出怎样的火花?或许周杰伦已经给了我们答案。8月29日下午,B站独家首发周杰伦限定珍藏Demo独家访谈VCR,周杰伦在VCR里分享了《晴天》《青花瓷》《搁浅》《爱在西元前》四首经典歌曲Demo背后的创作故事,并首次公布18年前未发布的神秘作品《纽约地铁》的Demo。在VCR中,方文山和杰威尔音乐提及到“多亏了区块链技术,现在我们可以将这些Demos,变成独一无二具有收藏价值的艺术品,这些Demos可以在薄盒(国内数藏平台)上听到。”如何将音乐与区块链技术相结合,薄盒方面称:“薄盒作为区块链技术服务方,打破传统对于区块链技术只能作为数字收藏的理解。聚焦于区块链技术赋能,在

  9. ruby - 为 IO::popen 拯救 "command not found" - 2

    当我将IO::popen与不存在的命令一起使用时,我在屏幕上打印了一条错误消息:irb>IO.popen"fakefake"#=>#irb>(irb):1:commandnotfound:fakefake有什么方法可以捕获此错误,以便我可以在脚本中进行检查? 最佳答案 是:升级到ruby​​1.9。如果您在1.9中运行它,则会引发Errno::ENOENT,您将能够拯救它。(编辑)这是在1.8中的一种hackish方式:error=IO.pipe$stderr.reopenerror[1]pipe=IO.popen'qwe'#

  10. ruby - IO::EAGAINWaitReadable:资源暂时不可用 - 读取会阻塞 - 2

    当我尝试使用“套接字”库中的方法“read_nonblock”时出现以下错误IO::EAGAINWaitReadable:Resourcetemporarilyunavailable-readwouldblock但是当我通过终端上的IRB尝试时它工作正常如何让它读取缓冲区? 最佳答案 IgetthefollowingerrorwhenItrytousethemethod"read_nonblock"fromthe"socket"library当缓冲区中的数据未准备好时,这是预期的行为。由于异常IO::EAGAINWaitReadab

随机推荐