标签: swift5

“UnsafePointer<UInt8>”的初始化导致悬空指针

试图清除我的 SWIFT 5/XCODE 项目中的一些警告,但我陷入了这一困境:

 let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
 let msgData = Data(bytes: UnsafePointer<UInt8>(sendBytes), count: sendBytes.count)
 socket.write(msgData, withTimeout: -1.0, tag: 0)
 socket.readData(withTimeout: -1.0, tag: 0)
        
Run Code Online (Sandbox Code Playgroud)

对于“UnsafePointer”,我收到以下警告和两条建议:

“UnsafePointer”的初始化导致悬空指针

  1. 从“[UInt8]”到“UnsafePointer”的隐式参数转换生成一个仅在调用“init(_:)”期间有效的指针

  2. 在数组上使用“withUnsafeBufferPointer”方法,以便将参数显式转换为对定义范围有效的缓冲区指针

这是我的解决方案,更好吗?

版本1:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, count: sendBytes.count)
let msgData = Data(bytes: uint8Pointer, count: sendBytes.count)
socket.write(msgData, withTimeout: -1.0, tag: 0)
socket.readData(withTimeout: -1.0, tag: 0)
Run Code Online (Sandbox Code Playgroud)

版本2:

let sendBytes:[UInt8] = [0x0, 0x0, 0x5, 0x0]                     
let uint8Pointer = UnsafeMutablePointer<UInt8>.allocate(capacity: sendBytes.count)
uint8Pointer.initialize(from: sendBytes, …
Run Code Online (Sandbox Code Playgroud)

xcode swift swift5

2
推荐指数
1
解决办法
2106
查看次数

不允许向本地主机发出请求 - swift

我无法在 swift 5、XCode 版本 11.6 (11E708) 和 iOS 13.6 中发布到服务器。我收到此错误:

2020-08-26 08:20:55.252545-0400 iris[1642:721953] Task <BBB3809B-7BEF-4F60-9685-774027ADA7E6>.<1> finished with error [-1022] Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection." UserInfo={NSUnderlyingError=0x2810ad710 {Error Domain=kCFErrorDomainCFNetwork Code=-1022 "(null)"}, NSErrorFailingURLStringKey=http://localhost:8000/searchImage/, NSErrorFailingURLKey=http://localhost:8000/searchImage/, NSLocalizedDescription=The resource could not be loaded because the App Transport Security policy requires the use of a secure connection.}
error=Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport …
Run Code Online (Sandbox Code Playgroud)

security xcode ios swift5

2
推荐指数
1
解决办法
6064
查看次数

对初始化程序 SwiftUI 的调用中没有完全匹配

我有以下代码。我向 json 文件添加了新项目,但由于某种原因,即使我添加了所有模型等,我也无法显示 team.Pos。原始数据有效,但新添加的数据无效。知道为什么吗?此外,我还尝试显示数组数据。但它又出现了同样的错误

import SwiftUI
struct TeamRow: View {
    var team: Team
    var body: some View {
        HStack {
            Image(team.iconName)
            Text(team.code)
            Text(team.Pos) // the error happens here
            Text(clubRanking[10]) // the same error happens
            Spacer()
            
        }
    }
}

struct TeamRow_Previews: PreviewProvider {
    static var previews: some View {
        TeamRow(team: teamData[0])
            .previewLayout(.fixed(width: 350, height: 70))
    }
}
Run Code Online (Sandbox Code Playgroud)

这是数据模型

import SwiftUI
import CoreLocation

struct Team: Hashable, Codable, Identifiable {
    var id: Int
    var name: String
    var nickname: String
    var iconName: String
    var …
Run Code Online (Sandbox Code Playgroud)

json view swift5 swiftui xcode12

2
推荐指数
1
解决办法
4321
查看次数

当引用循环不太可能发生时,在 @escaping 闭包中隐式 self Swift 5.3

使用SE-0269,我们将\xe2\x80\x99 在下面的情况下不再需要使用显式引用类型。

\n
class Test {\n    var x = 0\n    func execute(_ work: @escaping () -> Void) {\n        work()\n    }\n    func method() {\n        execute { [self] in\n            x += 1\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

这是否会处理[weak self]和[unowned self],或者我们应该在该提案中明确使用weak和unowned的情况。

\n

ios swift swift5

2
推荐指数
1
解决办法
882
查看次数

如何在 Swift 5 中向应用程序添加 AirPlay 按钮

我想实现一个 Airplay 按钮,显示蓝牙、iPhone 选项,就像在 iPhone 音乐应用程序中我们单击 Airplay 一样。我编写了一些代码,但遇到了一些问题。

  1. 当我实现时,MPVolumeView 工作正常,但无法更改按钮颜色。我检查了色调颜色但不起作用
  2. 添加了 AVRoutePickerView 的代码,它不起作用它不会触发,因此它不会显示 AirPlay 弹出视图
  3. 我想在单击 UIButton 时显示此 Airplay 弹出视图,但我找不到任何与此相关的解决方案,因此我采用 UIView 。

有一些链接适用于某些要点,但不适用于整个事情

自定义视图上的 AirPlay 按钮

https://developer.jwplayer.com/jwplayer/docs/ios-add-an-airplay-button-to-an-app

iOS - 如何在 Swift 中显示“AirPlay”弹出菜单?

请检查下面的屏幕截图以获取更多信息。

在此输入图像描述

请检查代码

import UIKit
import MediaPlayer
import AVKit

class TempDemoViewController: UIViewController {
    @IBOutlet weak var airPlayView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupAirPlayButton()
    }
    
    func setupAirPlayButton() {
        var buttonView: UIView = UIView()
        let buttonFrame = CGRect(x: 0, y: 0, width: 50, height: 50)
                
        if #available(iOS 11, *) { …
Run Code Online (Sandbox Code Playgroud)

avaudioplayer ios airplay swift swift5

2
推荐指数
1
解决办法
3488
查看次数

如何在 onSubmit 块中使用 swift wait 函数

我有一个包含搜索数据的列表。为了获取数据,我想调用await func(swift 5.5),但我收到此错误:

“无法将 '() async -> ()' 类型的函数传递给需要同步函数类型的参数”

这是我的代码:

struct ContentView: View {


@ObservedObject var twitterAPI: TwitterAPI = TwitterAPI()

@State private var searchText = "TheEllenShow" // TheEllenShow

var body: some View {
    NavigationView {
        VStack{
            if twitterAPI.twitterSearchResults?.resultDataVM != nil{
                List {
                    ForEach((twitterAPI.twitterSearchResults?.resultDataVM)!) { item in
                        Text(item.text)
                    }
                }
                .refreshable {
                    await twitterAPI.executeQuery(userName: searchText)
                }
            }else{
                Text("Loading")
            }
            Spacer()
            
            
        }
        .searchable(text: $searchText)
        .onSubmit(of: .search) {
            await twitterAPI.executeQuery(userName: searchText)
        }

        .navigationTitle("Twitter")
        
    }
    .task {
        await twitterAPI.executeQuery(userName: searchText)
    }
}  }
Run Code Online (Sandbox Code Playgroud)

synchronous async-await swift swift5 swiftui

2
推荐指数
1
解决办法
1293
查看次数

Swift 5.5:异步 @objc didPullToRefresh 选择器导致应用程序崩溃,并出现错误 EXC_BAD_ACCESS

我有一个表,其中添加了刷新控件,当我下拉刷新内容时,我重置为表提供数据的数组,然后立即通过 API 调用请求新数据。

到目前为止,我已经使用完成处理程序和协议将数据获取到表视图中,但由于网络调用和嵌套闭包金字塔所需的复杂性,我想将逻辑移至 async/await。

在 viewDidLoad 中填充视图工作正常,但使用 pullToRefresh 选择器时出现错误:

Thread 1: EXC_BAD_ACCESS (code=1, address=0xbcf917df8160)
Run Code Online (Sandbox Code Playgroud)

执行:

override func viewDidLoad() {
    super.viewDidLoad()
    setupView()
    setupTableView()
    setupTableRefreshControl()
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  } 
Run Code Online (Sandbox Code Playgroud)
func setupTableRefreshControl() {
    myTable.refreshControl = UIRefreshControl()
    myTable.refreshControl?.addTarget(self, action: #selector(didPullToRefresh), for: .valueChanged)
  }
Run Code Online (Sandbox Code Playgroud)

导致应用程序崩溃的代码:

   @objc func didPullToRefresh() async {
    balance.reset() // reset array to []
    Task {
      await getBalances() //async network call
      myTable.reloadData()
    }
  }
Run Code Online (Sandbox Code Playgroud)

ios async-await uirefreshcontrol swift5

2
推荐指数
1
解决办法
888
查看次数

如何在 Alamofire swift 5 中进行 SSL 公钥固定

我正在尝试将 SSL 公钥固定集成到 Alamofire swift 5 中,但我发现ServerTrustPolicyManager它已被弃用。请帮助我融入。谢谢。

ios swift alamofire public-key-pinning swift5

2
推荐指数
1
解决办法
4182
查看次数

SwipeActions 在 tableView swift 5 xcode 13.4.1 中不起作用

我正在对我的表格视图进行 TrailingSwipe 但它不起作用。不调用该函数trailingSwipeActionsConfigurationForRowAt

尝试使用leadingSwipeActionsConfigurationForRowAt,如果它对我有用,但对TrailingSwipe不起作用

有效的是我拥有表视图的委托和数据源

代码

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let delete = UIContextualAction(style: .normal, title: "delete2") {(action, view, completionHandler) in
            print("delete2 \(indexPath.row)")
        }
        let swipe = UISwipeActionsConfiguration(actions: [delete])
        return swipe
    }
Run Code Online (Sandbox Code Playgroud)

使用 Apple Mac M1 (MacBook Pro M1)

xcode ios swift swift5

2
推荐指数
1
解决办法
1496
查看次数

Swift 并发:为什么任务不在其他后台线程上执行

我正在尝试学习快速并发,但它带来了很多混乱。我知道 Task {} 是一个异步单元,它允许我们从同步上下文桥接异步函数调用。它类似于 DispatchQueue.Global() ,后者将在某个任意线程上执行该块。

override func viewDidLoad() {
        super.viewDidLoad()
        
        Task {
            do {
                    
                 let data = try await asychronousApiCall()
                 print(data)
                    
                } catch {
                    print("Request failed with error: \(error)")
                }
        }
        
        for i in 1...30000 {
            print("Thread \(Thread.current)")
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的 asychronousApiCall 函数如下

func asychronousApiCall() async throws -> Data {
        print("starting with asychronousApiCall")
        print("Thread \(Thread.current)")
        let url = URL(string: "https://www.stackoverflow.com")!
        // Use the async variant of URLSession to fetch data
        // Code might suspend here
        let (data, _) = …
Run Code Online (Sandbox Code Playgroud)

concurrency multithreading async-await swift swift5

2
推荐指数
1
解决办法
3975
查看次数