我有一个应用程序必须下载多个大文件.我想让它逐个下载每个文件,而不是并发.当它同时运行时,应用程序会重载并崩溃.

所以.我试图将一个downloadTaskWithURL包装在NSBlockOperation内,然后在队列中设置maxConcurrentOperationCount = 1.我在下面写了这段代码,但是由于两个文件同时被下载,所以没有工作.

import UIKit

class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDownloadDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        processURLs()        
    }

    func download(url: NSURL){
        let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession(configuration: sessionConfiguration,delegate: self,delegateQueue: nil)
        let downloadTask = session.downloadTaskWithURL(url)
        downloadTask.resume()
    }

    func processURLs(){

        //setup queue and set max conncurrent to 1
        var queue = NSOperationQueue()
        queue.name = "Download queue"
        queue.maxConcurrentOperationCount = 1

        let url = NSURL(string: "http://azspeastus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&sr=b&sig=%2FZNzdvvzwYO%2BQUbrLBQTalz%2F8zByvrUWD%2BDfLmkpZuQ%3D&se=2015-09-01T01%3A48%3A51Z&sp=r")
        let url2 = NSURL(string: "http://azspwestus.blob.core.windows.net/azurespeed/100MB.bin?sv=2014-02-14&sr=b&sig=ufnzd4x9h1FKmLsODfnbiszXd4EyMDUJgWhj48QfQ9A%3D&se=2015-09-01T01%3A48%3A51Z&sp=r")

        let urls = [url,url2]
        for url in urls {
            let operation = NSBlockOperation { () -> Void in
                println("starting download")
                self.download(url!)
            }

            queue.addOperation(operation)            
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // dispose of any resources that can be recreated.
    }

    func URLSession(session: NSURLSession,downloadTask: NSURLSessionDownloadTask,didFinishDownloadingToURL location: NSURL) {
        //code
    }

    func URLSession(session: NSURLSession,didResumeAtOffset fileOffset: Int64,expectedTotalBytes: Int64) {
        //
    }

    func URLSession(session: NSURLSession,didWriteData bytesWritten: Int64,totalBytesWritten: Int64,totalBytesExpectedToWrite: Int64) {
        var progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        println(progress)
    }

}

如何正确地写这个来实现我的目标,一次只能下载一个文件.

解决方法

您的代码将无法正常工作,因为NSURLSessionDownloadTask异步运行.因此,NSBlockOperation在下载完成之前完成,因此在操作顺序触发时,下载任务将以异步方式并行进行.

为了解决这个问题,您可以将请求包装在异步NSOperation子类中.有关更多信息,请参阅并发编程指南中的Configuring Operations for Concurrent Execution.

但是,在我说明如何在您的情况(基于委托的NSURLSession)之前,让我首先向您展示使用完成处理程序转换时更简单的解决方案.我们稍后会为您提出更复杂的问题.所以,在Swift 3:

class DownloadOperation : AsynchronousOperation {
    var task: URLSessionTask!

    init(session: URLSession,url: URL) {
        super.init()

        task = session.downloadTask(with: url) { temporaryURL,response,error in
            defer { self.completeOperation() }

            guard error == nil && temporaryURL != nil else {
                print("\(error)")
                return
            }

            do {
                let manager = FileManager.default
                let destinationURL = try manager.url(for: .documentDirectory,in: .userDomainMask,appropriateFor: nil,create: false)
                    .appendingPathComponent(url.lastPathComponent)
                _ = try? manager.removeItem(at: destinationURL)                    // remove the old one,if any
                try manager.moveItem(at: temporaryURL!,to: destinationURL)    // move new one there
            } catch let moveError {
                print("\(moveError)")
            }
        }
    }

    override func cancel() {
        task.cancel()
        super.cancel()
    }

    override func main() {
        task.resume()
    }

}

/// Asynchronous operation base class
///
/// This is abstract to class performs all of the necessary KVN of `isFinished` and
/// `isExecuting` for a concurrent `Operation` subclass. You can subclass this and
/// implement asynchronous operations. All you must do is:
///
/// - override `main()` with the tasks that initiate the asynchronous task;
///
/// - call `completeOperation()` function when the asynchronous task is done;
///
/// - optionally,periodically check `self.cancelled` status,performing any clean-up
///   necessary and then ensuring that `completeOperation()` is called; or
///   override `cancel` method,calling `super.cancel()` and then cleaning-up
///   and ensuring `completeOperation()` is called.

public class AsynchronousOperation : Operation {

    override public var isAsynchronous: Bool { return true }

    private let stateLock = NSLock()

    private var _executing: Bool = false
    override private(set) public var isExecuting: Bool {
        get {
            return stateLock.withCriticalScope { _executing }
        }
        set {
            willChangeValue(forKey: "isExecuting")
            stateLock.withCriticalScope { _executing = newValue }
            didChangeValue(forKey: "isExecuting")
        }
    }

    private var _finished: Bool = false
    override private(set) public var isFinished: Bool {
        get {
            return stateLock.withCriticalScope { _finished }
        }
        set {
            willChangeValue(forKey: "isFinished")
            stateLock.withCriticalScope { _finished = newValue }
            didChangeValue(forKey: "isFinished")
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    public func completeOperation() {
        if isExecuting {
            isExecuting = false
        }

        if !isFinished {
            isFinished = true
        }
    }

    override public func start() {
        if isCancelled {
            isFinished = true
            return
        }

        isExecuting = true

        main()
    }
}

/*
    copyright (C) 2015 Apple Inc. All Rights Reserved.
    See LICENSE.txt for this sample’s licensing information

    Abstract:
    An extension to `NSLock` to simplify executing critical code.

    From Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/
    From https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip
*/

extension NSLock {

    /// Perform closure within lock.
    ///
    /// An extension to `NSLock` to simplify executing critical code.
    ///
    /// - parameter block: The closure to be performed.

    func withCriticalScope<T>(block: () -> T) -> T {
        lock()
        let value = block()
        unlock()
        return value
    }
}

或在Swift 2:

/// Asynchronous NSOperation subclass for downloading

class DownloadOperation : AsynchronousOperation {
    var task: NSURLSessionTask!

    init(session: NSURLSession,URL: NSURL) {
        super.init()

        task = session.downloadTaskWithURL(URL) { temporaryURL,error in
            defer {
                self.completeOperation()
            }

            print(URL.lastPathComponent)

            guard error == nil && temporaryURL != nil else {
                print(error)
                return
            }

            do {
                let manager = NSFileManager.defaultManager()
                let documents = try manager.URLForDirectory(.DocumentDirectory,inDomain: .UserDomainMask,appropriateForURL: nil,create: false)
                let destinationURL = documents.URLByAppendingPathComponent(URL.lastPathComponent!)
                if manager.fileExistsAtPath(destinationURL.path!) {
                    try manager.removeItemAtURL(destinationURL)
                }
                try manager.moveItemAtURL(temporaryURL!,toURL: destinationURL)
            } catch let moveError {
                print(moveError)
            }
        }
    }

    override func cancel() {
        task.cancel()
        super.cancel()
    }

    override func main() {
        task.resume()
    }

}


//
//  AsynchronousOperation.swift
//
//  Created by Robert Ryan on 9/20/14.
//  copyright (c) 2014 Robert Ryan. All rights reserved.
//

import Foundation

/// Asynchronous Operation base class
///
/// This class performs all of the necessary KVN of `isFinished` and
/// `isExecuting` for a concurrent `NSOperation` subclass. So,to developer
/// a concurrent NSOperation subclass,you instead subclass this class which:
///
/// - must override `main()` with the tasks that initiate the asynchronous task;
///
/// - must call `completeOperation()` function when the asynchronous task is done;
///
/// - optionally,calling `super.cancel()` and then cleaning-up
///   and ensuring `completeOperation()` is called.

public class AsynchronousOperation : NSOperation {

    override public var asynchronous: Bool { return true }

    private let stateLock = NSLock()

    private var _executing: Bool = false
    override private(set) public var executing: Bool {
        get {
            return stateLock.withCriticalScope { _executing }
        }
        set {
            willChangeValueForKey("isExecuting")
            stateLock.withCriticalScope { _executing = newValue }
            didChangeValueForKey("isExecuting")
        }
    }

    private var _finished: Bool = false
    override private(set) public var finished: Bool {
        get {
            return stateLock.withCriticalScope { _finished }
        }
        set {
            willChangeValueForKey("isFinished")
            stateLock.withCriticalScope { _finished = newValue }
            didChangeValueForKey("isFinished")
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    public func completeOperation() {
        if executing {
            executing = false
        }

        if !finished {
            finished = true
        }
    }

    override public func start() {
        if cancelled {
            finished = true
            return
        }

        executing = true

        main()
    }

    override public func main() {
        fatalError("subclasses must override `main`")
    }
}

/*
    copyright (C) 2015 Apple Inc. All Rights Reserved.
    See LICENSE.txt for this sample’s licensing information

    Abstract:
    An extension to `NSLock` to simplify executing critical code.

    From Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/
    From https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip
*/

import Foundation

extension NSLock {

    /// Perform closure within lock.
    ///
    /// An extension to `NSLock` to simplify executing critical code.
    ///
    /// - parameter block: The closure to be performed.

    func withCriticalScope<T>(@noescape block: Void -> T) -> T {
        lock()
        let value = block()
        unlock()
        return value
    }
}

那你可以做:

for url in urls {
    queue.addOperation(DownloadOperation(session: session,url: url))
}

所以这是在异步操作/ NSOperation子类中包装异步URLSession / NSURLSession请求的一种非常简单的方法.更一般地说,这是一个有用的模式,使用AsynchronousOperation来在Operation / NSOperation对象中包装一些异步任务.

不幸的是,在您的问题中,您希望使用基于委托的URLSession / NSURLSession,以便您可以监控下载的进度.这更复杂

这是因为在会话对象的委托中调用了“任务完成”NSURLSession委托方法.这是NSURLSession的一个令人激动的设计功能(但是苹果做了简化后台会话,这在这里是不相关的,但我们坚持设计限制).

但是,随着任务的完成,我们必须异步地完成操作.所以我们需要一些方法来解决当didCompleteWithError被调用时用操作来完成.现在你可以让每个操作都有自己的NSURLSession对象,但事实证明这是非常低效的.

所以,为了处理这一点,我维护一个字典,由任务的taskIdentifier键入,它标识适当的操作.这样,当下载完成后,您可以“完成”正确的异步操作.所以,在Swift 3:

/// Manager of asynchronous download `Operation` objects

class DownloadManager: NSObject {

    /// Dictionary of operations,keyed by the `taskIdentifier` of the `URLSessionTask`

    fileprivate var operations = [Int: DownloadOperation]()

    /// Serial NSOperationQueue for downloads

    private let queue: OperationQueue = {
        let _queue = OperationQueue()
        _queue.name = "download"
        _queue.maxConcurrentOperationCount = 1    // I'd usually use values like 3 or 4 for performance reasons,but OP asked about downloading one at a time

        return _queue
    }()

    /// Delegate-based NSURLSession for DownloadManager

    lazy var session: URLSession = {
        let configuration = URLSessionConfiguration.default
        return URLSession(configuration: configuration,delegateQueue: nil)
    }()

    /// Add download
    ///
    /// - parameter URL:  The URL of the file to be downloaded
    ///
    /// - returns:        The DownloadOperation of the operation that was queued

    @discardableResult
    func addDownload(_ url: URL) -> DownloadOperation {
        let operation = DownloadOperation(session: session,url: url)
        operations[operation.task.taskIdentifier] = operation
        queue.addOperation(operation)
        return operation
    }

    /// Cancel all queued operations

    func cancelAll() {
        queue.cancelAllOperations()
    }

}

// MARK: URLSessionDownloadDelegate methods

extension DownloadManager: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession,downloadTask: URLSessionDownloadTask,didFinishDownloadingTo location: URL) {
        operations[downloadTask.taskIdentifier]?.urlSession(session,downloadTask: downloadTask,didFinishDownloadingTo: location)
    }

    func urlSession(_ session: URLSession,totalBytesExpectedToWrite: Int64) {
        operations[downloadTask.taskIdentifier]?.urlSession(session,didWriteData: bytesWritten,totalBytesWritten: totalBytesWritten,totalBytesExpectedToWrite: totalBytesExpectedToWrite)
    }
}

// MARK: URLSessionTaskDelegate methods

extension DownloadManager: URLSessionTaskDelegate {

    func urlSession(_ session: URLSession,task: URLSessionTask,didCompleteWithError error: Error?)  {
        let key = task.taskIdentifier
        operations[key]?.urlSession(session,task: task,didCompleteWithError: error)
        operations.removeValue(forKey: key)
    }

}

/// Asynchronous Operation subclass for downloading

class DownloadOperation : AsynchronousOperation {
    let task: URLSessionTask

    init(session: URLSession,url: URL) {
        task = session.downloadTask(with: url)
        super.init()
    }

    override func cancel() {
        task.cancel()
        super.cancel()
    }

    override func main() {
        task.resume()
    }
}

// MARK: NSURLSessionDownloadDelegate methods

extension DownloadOperation: URLSessionDownloadDelegate {

    func urlSession(_ session: URLSession,didFinishDownloadingTo location: URL) {
        do {
            let manager = FileManager.default
            let destinationURL = try manager.url(for: .documentDirectory,create: false)
                .appendingPathComponent(downloadTask.originalRequest!.url!.lastPathComponent)
            if manager.fileExists(atPath: destinationURL.path) {
                try manager.removeItem(at: destinationURL)
            }
            try manager.moveItem(at: location,to: destinationURL)
        } catch {
            print("\(error)")
        }
    }

    func urlSession(_ session: URLSession,totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("\(downloadTask.originalRequest!.url!.absoluteString) \(progress)")
    }
}

// MARK: NSURLSessionTaskDelegate methods

extension DownloadOperation: URLSessionTaskDelegate {

    func urlSession(_ session: URLSession,didCompleteWithError error: Error?)  {
        completeOperation()
        if error != nil {
            print("\(error)")
        }
    }

}

或在Swift 2:

/// Manager of asynchronous NSOperation objects

class DownloadManager: NSObject,NSURLSessionTaskDelegate,NSURLSessionDownloadDelegate {

    /// Dictionary of operations,keyed by the `taskIdentifier` of the `NSURLSessionTask`

    private var operations = [Int: DownloadOperation]()

    /// Serial NSOperationQueue for downloads

    let queue: NSOperationQueue = {
        let _queue = NSOperationQueue()
        _queue.name = "download"
        _queue.maxConcurrentOperationCount = 1

        return _queue
    }()

    /// Delegate-based NSURLSession for DownloadManager

    lazy var session: NSURLSession = {
        let sessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
        return NSURLSession(configuration: sessionConfiguration,delegateQueue: nil)
    }()

    /// Add download
    ///
    /// - parameter URL:  The URL of the file to be downloaded
    ///
    /// - returns:        The DownloadOperation of the operation that was queued

    func addDownload(url: NSURL) -> DownloadOperation {
        let operation = DownloadOperation(session: session,URL: url)
        operations[operation.task.taskIdentifier] = operation
        queue.addOperation(operation)
        return operation
    }

    /// Cancel all queued operations

    func cancelAll() {
        queue.cancelAllOperations()
    }

    // MARK: NSURLSessionDownloadDelegate methods

    func URLSession(session: NSURLSession,didFinishDownloadingToURL location: NSURL) {
        operations[downloadTask.taskIdentifier]?.URLSession(session,didFinishDownloadingToURL: location)
    }

    func URLSession(session: NSURLSession,totalBytesExpectedToWrite: Int64) {
        operations[downloadTask.taskIdentifier]?.URLSession(session,totalBytesExpectedToWrite: totalBytesExpectedToWrite)
    }

    // MARK: NSURLSessionTaskDelegate methods

    func URLSession(session: NSURLSession,task: NSURLSessionTask,didCompleteWithError error: NSError?) {
        let key = task.taskIdentifier
        operations[key]?.URLSession(session,didCompleteWithError: error)
        operations.removeValueForKey(key)
    }

}

/// Asynchronous NSOperation subclass for downloading

class DownloadOperation : AsynchronousOperation {
    let task: NSURLSessionTask

    init(session: NSURLSession,URL: NSURL) {
        task = session.downloadTaskWithURL(URL)
        super.init()
    }

    override func cancel() {
        task.cancel()
        super.cancel()
    }

    override func main() {
        task.resume()
    }

    // MARK: NSURLSessionDownloadDelegate methods

    func URLSession(session: NSURLSession,didFinishDownloadingToURL location: NSURL) {
        do {
            let manager = NSFileManager.defaultManager()
            let documents = try manager.URLForDirectory(.DocumentDirectory,create: false)
            let destinationURL = documents.URLByAppendingPathComponent(downloadTask.originalRequest!.URL!.lastPathComponent!)
            if manager.fileExistsAtPath(destinationURL.path!) {
                try manager.removeItemAtURL(destinationURL)
            }
            try manager.moveItemAtURL(location,toURL: destinationURL)
        } catch {
            print(error)
        }
    }

    func URLSession(session: NSURLSession,totalBytesExpectedToWrite: Int64) {
        let progress = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
        print("\(downloadTask.originalRequest!.URL!.absoluteString) \(progress)")
    }

    // MARK: NSURLSessionTaskDelegate methods

    func URLSession(session: NSURLSession,didCompleteWithError error: NSError?) {
        completeOperation()
        if error != nil {
            print(error)
        }
    }

}

然后我就这样使用它:

let downloadManager = DownloadManager()

override func viewDidLoad() {
    super.viewDidLoad()

    let urlStrings = [
        "http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/s72-55482.jpg","http://spaceflight.nasa.gov/gallery/images/apollo/apollo10/hires/as10-34-5162.jpg","http://spaceflight.nasa.gov/gallery/images/apollo-soyuz/apollo-soyuz/hires/s75-33375.jpg","http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-134-20380.jpg","http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-140-21497.jpg","http://spaceflight.nasa.gov/gallery/images/apollo/apollo17/hires/as17-148-22727.jpg"
    ]
    let urls = urlStrings.flatMap { URL(string: $0) }   // use NSURL in Swift 2

    for url in urls {
        downloadManager.addDownload(url)
    }

}

ios – 如何下载多个文件顺序使用NSURLSession downloadTask在Swift的更多相关文章

  1. HTML5 播放 RTSP 视频的实例代码

    目前大多数网络摄像头都是通过 RTSP 协议传输视频流的,但是 HTML 并不标准支持 RTSP 流。本文重点给大家介绍HTML5 播放 RTSP 视频的实例代码,需要的朋友参考下吧

  2. 浅析HTML5中的download属性使用

    这篇文章主要介绍了浅析HTML5中的download属性使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  3. HTML5 Web缓存和运用程序缓存(cookie,session)

    这篇文章主要介绍了HTML5 Web缓存和运用程序缓存(cookie,session),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

  4. HTML5 Blob 实现文件下载功能的示例代码

    这篇文章主要介绍了HTML5 Blob 实现文件下载功能的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  5. web字体加载方案优化小结

    这篇文章主要介绍了web字体加载方案优化小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

  6. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  7. iOS Swift上弃用后Twitter.sharedInstance().session()?. userName的替代方案

    解决方法如果您仍在寻找解决方案,请参阅以下内容:

  8. 使用Fabric SDK iOS访问Twitter用户时间线

    我试图在这个问题上挣扎两天.我正在使用FabricSDK和Rest工具包,试图为Twitter使用不同的RestAPIWeb服务.我可以使用具有authTokenSecret,authToken和其他值的会话对象的TWTRLogInButton成功登录.当我尝试获取用户时间线时,我总是得到失败的响应,作为:{“errors”:[{“code”:215,“message”:“BadAuthentic

  9. ios – 加载空白页面的SFSafariViewController

    我正在使用SFSafariViewController在我的iOS应用程序中打开一个URL..它在iOS9上完美运行但在将我的设备更新到iOS10后,它只是在地址栏中加载了一个没有URL的空白页面.甚至safariViewController(控制器:SFSafariViewController,didCompleteInitialLoaddidLoadSuccessfully:Bool)在控制器

  10. ios – 如何从Apple Watch调用iPhone上定义的方法

    有没有办法从Watchkit扩展中调用iPhone上的类中定义的方法?根据我的理解,目前在Watchkit和iPhone之间进行本地通信的方法之一是使用NSUserDefaults,但还有其他方法吗?

随机推荐

  1. iOS实现拖拽View跟随手指浮动效果

    这篇文章主要为大家详细介绍了iOS实现拖拽View跟随手指浮动,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

  2. iOS – genstrings:无法连接到输出目录en.lproj

    使用我桌面上的项目文件夹,我启动终端输入:cd然后将我的项目文件夹拖到终端,它给了我路径.然后我将这行代码粘贴到终端中找.-name*.m|xargsgenstrings-oen.lproj我在终端中收到此错误消息:genstrings:无法连接到输出目录en.lproj它多次打印这行,然后说我的项目是一个目录的路径?没有.strings文件.对我做错了什么的想法?

  3. iOS 7 UIButtonBarItem图像没有色调

    如何确保按钮图标采用全局色调?解决方法只是想将其转换为根注释,以便为“回答”复选标记提供更好的上下文,并提供更好的格式.我能想出这个!

  4. ios – 在自定义相机层的AVFoundation中自动对焦和自动曝光

    为AVFoundation定制图层相机创建精确的自动对焦和曝光的最佳方法是什么?

  5. ios – Xcode找不到Alamofire,错误:没有这样的模块’Alamofire’

    我正在尝试按照github(https://github.com/Alamofire/Alamofire#cocoapods)指令将Alamofire包含在我的Swift项目中.我创建了一个新项目,导航到项目目录并运行此命令sudogeminstallcocoapods.然后我面临以下错误:搜索后我设法通过运行此命令安装cocoapodssudogeminstall-n/usr/local/bin

  6. ios – 在没有iPhone6s或更新的情况下测试ARKit

    我在决定下载Xcode9之前.我想玩新的框架–ARKit.我知道要用ARKit运行app我需要一个带有A9芯片或更新版本的设备.不幸的是我有一个较旧的.我的问题是已经下载了新Xcode的人.在我的情况下有可能运行ARKit应用程序吗?那个或其他任何模拟器?任何想法或我将不得不购买新设备?解决方法任何iOS11设备都可以使用ARKit,但是具有高质量AR体验的全球跟踪功能需要使用A9或更高版本处理器的设备.使用iOS11测试版更新您的设备是必要的.

  7. 将iOS应用移植到Android

    我们制作了一个具有2000个目标c类的退出大型iOS应用程序.我想知道有一个最佳实践指南将其移植到Android?此外,由于我们的应用程序大量使用UINavigation和UIView控制器,我想知道在Android上有类似的模型和实现.谢谢到目前为止,guenter解决方法老实说,我认为你正在计划的只是制作难以维护的糟糕代码.我意识到这听起来像很多工作,但从长远来看它会更容易,我只是将应用程序的概念“移植”到android并从头开始编写.

  8. ios – 在Swift中覆盖Objective C类方法

    我是Swift的初学者,我正在尝试在Swift项目中使用JSONModel.我想从JSONModel覆盖方法keyMapper,但我没有找到如何覆盖模型类中的Objective-C类方法.该方法的签名是:我怎样才能做到这一点?解决方法您可以像覆盖实例方法一样执行此操作,但使用class关键字除外:

  9. ios – 在WKWebView中获取链接URL

    我想在WKWebView中获取tapped链接的url.链接采用自定义格式,可触发应用中的某些操作.例如HTTP://我的网站/帮助#深层链接对讲.我这样使用KVO:这在第一次点击链接时效果很好.但是,如果我连续两次点击相同的链接,它将不报告链接点击.是否有解决方法来解决这个问题,以便我可以检测每个点击并获取链接?任何关于这个的指针都会很棒!解决方法像这样更改addobserver在observeValue函数中,您可以获得两个值

  10. ios – 在Swift的UIView中找到UILabel

    我正在尝试在我的UIViewControllers的超级视图中找到我的UILabels.这是我的代码:这是在Objective-C中推荐的方式,但是在Swift中我只得到UIViews和CALayer.我肯定在提供给这个方法的视图中有UILabel.我错过了什么?我的UIViewController中的调用:解决方法使用函数式编程概念可以更轻松地实现这一目标.

返回
顶部