小编Pit*_*Pan的帖子

将新Object添加到Realm中的现有List

我有两节课.首先看起来像这样:

class Person: Object {
    dynamic var owner: String?
    var dogs: List<Dogs>()
}
Run Code Online (Sandbox Code Playgroud)

和第二类看起来像这样:

class Dogs: Object {
    dynamic var name: String?
    dynamic var age: String?
}
Run Code Online (Sandbox Code Playgroud)

现在在ViewController'viewDidLoad'中我Person用空创建对象List并将其保存在Realm中

func viewDidLoad(){
    let person = Person()
    person.name = "Tomas"
    try! realm.write {
        realm.add(Person.self)
    }
}
Run Code Online (Sandbox Code Playgroud)

它的伟大工程,我能创造Person,当我尝试读取这个数据的问题开始SecondViewControllerViewDidLoad做这件事:

var persons: Results<Person>?

func viewDidLoad(){
    persons = try! realm.allObjects()
}
Run Code Online (Sandbox Code Playgroud)

并尝试新添加DogList按钮的动作做:

@IBAction func addDog(){
    let newDog = Dogs()
    newDog.name = …
Run Code Online (Sandbox Code Playgroud)

realm ios swift realm-list

9
推荐指数
1
解决办法
8925
查看次数

如何在ViewController中将AVPlayer添加到UIView

UIViewController有一个插座UIView,我想用外部链接显示视频.在这种情况下,我尝试创建AVPlayerLayer并添加到我的UIView插座.

我的代码看起来像这样:

class VievController: UICollectionViewController {
    @IBOutlet weak var playerView: UIView!

    override func viewDidLoad(){
            let playerItem = AVPlayerItem(URL: NSURL(string: ("https://www.youtube.com/watch?v=_yE_XgoWBso"))!)
            let avPlayer = AVPlayer(playerItem: playerItem)
            let playerLayer = AVPlayerLayer(player: avPlayer)
            playerLayer.frame = playerView.bounds
            playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            playerView.layer.addSublayer(playerLayer)
            avPlayer.play()
    }
}//end class
Run Code Online (Sandbox Code Playgroud)

我不知道为什么我的UIVIew插座上没有看到视频- 什么都没发生.你有什么建议我应该修理什么吗?

uiview ios avplayer avplayerlayer swift

8
推荐指数
1
解决办法
6847
查看次数

MailComposer didFinishWith结果在Swift 3.0中不起作用

我将我的应用程序转换为swift 3.0并遇到问题MailComposeController.当我调用函数时:

`func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?){
    controller.dismiss(animated: true, completion: nil)
}`
Run Code Online (Sandbox Code Playgroud)

首先,我有一个错误的信息: 在此输入图像描述

我有什么奇怪的,因为我复制并粘贴了这个方法MFMailComposeViewControllerDelegate.当我Error改为NSError它工作,但我收到一个警告信息,这个方法需要是私人的,以避免这个警告.

当我在mailComposer并看到电子邮件并尝试点击Cancel此控制器时不会消失.任何解决方案如何解雇这个控制器?

ios mfmailcomposer swift swift3

5
推荐指数
1
解决办法
930
查看次数

如何在 WebKit 中处理重定向网站

我需要在WKWebView.

在开始时,viewDidLoad我创建请求并将其加载到webView. 它看起来像这样:

let request = URLRequest(url: URL(string: https://example.com/)!)
webView.navigationDelegate = self
webView.load(request)
Run Code Online (Sandbox Code Playgroud)

然后网站webView将我重定向到另一个网站,例如https://www.NEWSITE.com 如何识别/处理此重定向并在我的应用程序中打印这个新的 url 地址?有什么建议?

更新:委托方法中的解决方案

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
    print(navigationAction.request.url)
    decisionHandler(.allow)
}
Run Code Online (Sandbox Code Playgroud)

webkit ios url-redirection swift wkwebview

5
推荐指数
0
解决办法
3170
查看次数

莫亚更改网址

我尝试使用Google PlacesAPI 调用Moya,但 URL 出现问题。Maya更改我的网址中的字符。在这种情况下,例如在字符?添加%3f和更改,之前%2C。当我将此地址复制并粘贴到网络浏览器中时,我收到错误,但当我删除%3f和更改时%2C,我收到了 API 形式的正确答案。Moya如果我不想更改网址中的这些字符,我应该设置什么?

我的Moya提供者看起来像这样:

extension GooglePlacesService: TargetType {

var baseURL: URL {
    return URL(string: "https://maps.googleapis.com")!
}

var path: String {
    switch self {
    case .gasStation:
        return "/maps/api/place/nearbysearch/json?"
    }
}

var parameters: [String : Any]? {
    switch self {
    case .gasStation(let lat, let long, let type):
        return ["location": "\(lat),\(long)", "type" : "gas_station", "rankby" …
Run Code Online (Sandbox Code Playgroud)

ios google-places-api google-maps-sdk-ios swift moya

4
推荐指数
1
解决办法
2831
查看次数

如何在 UITableViewDiffableDataSource 中添加标题名称

我尝试为 中的每个部分添加标题UITableView,但在这种情况下UITableViewDiffableDataSource,我不知道应该在哪里做。我的代码的一部分:

private func prepareTableView() {
    tableView.delegate = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
    dataSource = UITableViewDiffableDataSource<Sections, User>(tableView: tableView, cellProvider: { (tableView, indexPath, user) -> UITableViewCell? in
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = user.name
        return cell
    })
}

private func addElement(_ user: User) {
    var snap = NSDiffableDataSourceSnapshot<Sections, User>()
    snap.appendSections([.main, .second])
    if isFirst {
        users.append(user)
    } else {
        secondUsers.append(user)
    }
    snap.appendItems(users, toSection: .main)
    snap.appendItems(secondUsers, toSection: .second)
    isFirst.toggle()
    dataSource.apply(snap, animatingDifferences: true, completion: nil)
    dataSource.defaultRowAnimation = .fade …
Run Code Online (Sandbox Code Playgroud)

uitableview swift diffabledatasource nsdiffabledatasourcesnapshot

3
推荐指数
1
解决办法
1551
查看次数

保留循环关闭

我尝试实现 Coordinator 模式的一些变体,但我在关闭时遇到了保留循环的问题。它看起来像这样:

func goTo() {
    let coord = SecondViewCoordinator(nav: navigationController)
    add(coord)
    coord.start()
    coord.deinitIfNeeded = { [weak self] in
        guard let self = self else { return }
        self.free(coord)
    }
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我设置deinitIfNeeded然后,如果在SecondViewCoordinator调用中deinitIfNeeded?()控制器正确弹出,但SecondViewCoordinator即使childCoordinators数组为空,对is 的引用仍然存在。

我的 Coordinator 类看起来像这样:

func goTo() {
    let coord = SecondViewCoordinator(nav: navigationController)
    add(coord)
    coord.start()
    coord.deinitIfNeeded = { [weak self] in
        guard let self = self else { return }
        self.free(coord)
    }
}
Run Code Online (Sandbox Code Playgroud)

内存图显示:

在此处输入图片说明

有任何想法吗?

arrays reference retain ios swift

3
推荐指数
1
解决办法
162
查看次数

许多任务中的一种方法 async/await

您好,我有一个情况,我需要在多个任务中调用相同的方法。我希望能够一一调用此方法(同步)而不是在并行模式下。看起来像这样:

var isReadyToRefresh: Bool = true

func refresh(value: Int) async {
    try! await Task.sleep(nanoseconds: 100_000_000) // imitation API CALL
    isReadyToRefresh = false
    print("Try to refresh: \(value)")
}

func mockCallAPI(value: Int) async {
    if isReadyToRefresh {
        await refresh(value: value)
    }
}

Task {
     await mockCallAPI(value: 1)
}

Task {
     await mockCallAPI(value: 2)
}
Run Code Online (Sandbox Code Playgroud)

输出:

尝试刷新:1

尝试刷新:2

我所需的输出:

尝试刷新:1 或尝试刷新 2。取决于第一个任务被调用。

有任何想法吗?

task grand-central-dispatch async-await swift urlsession

3
推荐指数
1
解决办法
1377
查看次数

如何更改SearchBar边框颜色

我想改变我Search Bar的白色灰色边框颜色.现在它看起来像这样:

搜索栏

使用这行代码后我实现了这个效果,但"内部边框"仍然是灰色的:

var searchBar: UISearchController!

    self.searchBar.searchBar.backgroundColor = UIColor.whiteColor()
    self.searchBar.searchBar.layer.borderWidth = 3
    self.searchBar.searchBar.layer.borderColor = UIColor.whiteColor().CGColor
    self.searchBar.searchBar.layer.backgroundColor = UIColor.whiteColor().CGColor
    self.searchBar.searchBar.tintColor = UIColor(red: 0.3, green: 0.63, blue: 0.22, alpha: 1)
Run Code Online (Sandbox Code Playgroud)

有人可以帮助我吗?

iphone uisearchbar ios swift

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

无法完成购买非续订订阅交易

我想在我的应用程序中实现年度订阅,我使用StoreKit. 问题是,当我点击subscriptionButton. 抛出错误的应用程序:'NSInvalidArgumentException', reason: 'Cannot finish a purchasing transaction'。我被困在这个地方,无法解决我的问题。所以,我的paymentQueue代码看起来像这样:

func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
    print(transactions)
    for transaction in transactions {
        print(transaction.error ?? "")
        switch transaction.transactionState {
        case .deferred:
            print("deffered")

        case let .failed(err):
            print("failed: \(err)")
        case .purchased:
            let productID = p.productIdentifier
            selectProduct(productID: productID)
        case .purchasing:
            print("purhasing")
            print("produkt name: \(p.localizedTitle)") // after executing this line of code app crashes
        case .restored:
            let productID = p.productIdentifier
            selectProduct(productID: productID)
        }
        queue.finishTransaction(transaction)
    }
} …
Run Code Online (Sandbox Code Playgroud)

storekit ios swift skpaymenttransaction

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

在segue到新的ViewController之后,搜索栏不会消失

Search Bar塞维到新的后不想消失ViewController.我创建search bar它:

    self.searchBar = UISearchController(searchResultsController: nil)
    self.searchBar.searchResultsUpdater = self
    self.searchBar.dimsBackgroundDuringPresentation = false


    self.navigationController?.extendedLayoutIncludesOpaqueBars = true
    self.tableView.tableHeaderView = self.searchBar.searchBar
    self.tableView.reloadData()
Run Code Online (Sandbox Code Playgroud)

for segue to new View Controllerfrom TableViewControllerI使用此函数:

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

   self.performSegueWithIdentifier("ContentViewCOntroller", sender: self)       
} 
Run Code Online (Sandbox Code Playgroud)

这张照片中的更多细节:

我搜索数据的第一个TableController

第二个带有SearchBar的ViewControler,它可能会降低成本,但它仍然存在

iphone uisearchbar ios swift uisearchcontroller

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

如何使用AVFundation打印格式为00:00:00的音频时间

在我的应用程序,我用AVFoundation我称之为功能showCurrentAudioProgress()使用NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: "showCurrentAudioProgress", userInfo: nil, repeats: true)viewDidLoad。我想返回这种时间格式00:00:00,但是我有一个大问题。整个功能如下所示:

var musicPlayer = AVAudioPLayer()

func showCurrentAudioProgress() {
    self.totalTimeOfAudio = self.musicPlayer.duration
    self.currentTimeOfAudio = self.musicPlayer.currentTime

    let progressToShow = Float(self.currentTimeOfAudio) / Float(self.totalTimeOfAudio)
    self.audioProgress.progress = progressToShow

    var totalTime = self.musicPlayer.duration
    totalTime -= self.currentTimeOfAudio

    self.currentTimeTimer.text = "\(currentTimeOfAudio)"
    self.AudioDurationTime.text = "\(totalTime)"  
}
Run Code Online (Sandbox Code Playgroud)

如何将我收到的时间转换AVAudioPlayer为00:00:00?

iphone time avfoundation ios swift

0
推荐指数
1
解决办法
900
查看次数

如何从我的应用程序中的UIWebView打开外部链接,但在Safari中?迅速

我想打开我的应用程序中的所有外部链接(UIWebView)不在应用程序内部,而是在Safari中.我怎样才能做到这一点?我已经实现了UiWebViewDelegate.

我的问题的工作解决方案如下:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked{
    UIApplication.sharedApplication().openURL(request.URL!)
    return false
}
    return true
}
Run Code Online (Sandbox Code Playgroud)

safari uiwebview ios swift

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